注解
1、简单模拟题。
2、从左到右遍历字符串,如果当前字符与前一个字符相同,则count++,否则把前一个字符及count写入到答案字符串中。
3、需要注意边界条件的处理:起始位置和终止位置。
4、还需要用到字符串与整型的相互转换,用stringstream处理。
代码
#include <iostream>
#include <sstream>
using namespace std;
string intToStr(int n) {
stringstream ss;
ss<<n;
string s;
ss>>s;
return s;
}
int main() {
int n;
cin>>n;
for(int i=0; i<n; i++) {
string s;
cin>>s;
string ans = "";
int count = 1;
for(int j=1; j<s.length(); j++) {
if(s.at(j)!=s.at(j-1)) {
if(count>1) {
ans += intToStr(count);
}
ans += s.at(j-1);
count = 1;
} else {
count++;
}
}
if(count>1) {
ans += intToStr(count);
}
ans += s.at(s.length()-1);
cout<<ans<<endl;
}
return 0;
}