替换字符串
给定一个字符串,请你将字符串重新编码,将连续的字符替换成“连续出现的个数+字符”。比如字符串AAAABCCDAA会被编码成4A1B2C1D2A。
输入描述:
每个测试输入包含1个测试用例 每个测试用例输入只有一行字符串,字符串只包括大写英文字母,长度不超过10000。
#include <iostream> #include <sstream> using namespace std; string IntToString(int number) { stringstream stream; stream << number; string res; stream >> res; return res; } string CalString(string& str) { if (str.size() == 0) return str; int start = 0; int end = 0; string res = ""; string wordLen = ""; for (int i = 0; i <= str.size(); i++) { if (str[start] != str[i]) { end = i; wordLen = IntToString(end - start); res += wordLen + str[start]; start = i; } } return res; } int main() { std::string input; std::getline(std::cin, input); std::string res = CalString(input); cout << res << endl; }