题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2886
分析:
对于每一个字符串中的字符,判断是否与之前的字符相同,如相同则计数加1,否则输出计数和之前的字符,记录新字符并重新计数。注意for循环外要输出最后的计数及字符。
C++实现:
/*
Sample Input
3
122344111
1111111111
12345
Sample Output
1122132431
101
1112131415 */
#include <iostream>
#include <string>
int main()
{
std::string str;
int len;
std::cin >> len;
for(int i = 0; i < len; ++i)
{
std::cin >> str;
char tmp = str[0];
int count = 1;
int idx = 0;
for(int j = 1; j < str.size(); ++j)
{
if(str[j] == tmp)
{
++count;
}
else
{
std::cout << count << tmp;
tmp = str[j];
count = 1;
}
}
std::cout << count << tmp << std::endl;
}
return 0;
}
感谢阅读,欢迎评论!