题目描述
分析
思路比较简单,每次找到某一个数字的起止位置,并计算其个数即可。主要有两种方法:
在线处理
把字符串遍历一遍,遍历的过程中判断字符s[i]是否与当前字符now相同,不同则将now及其个数加入到temp的后面,并把temp赋值给s(因为每次是对s进行操作)。
注意:结尾的部分跳出循环了但是并没有加到后面。
#include<iostream>
#include<string>
using namespace std;
int main() {
string s; int n;
cin >> s >> n;
while (--n) {
string temp;
char now = s[0]; int num = 0; //初始化,now表示当前位置的字符
for (int i = 0; i < s.size(); i++) {
if (s[i] != now) {
temp += now; temp += num + '0';
now = s[i]; num = 1;
}
else num++;
}
temp += now; temp += num + '0'; //结尾的部分跳出循环了但是并没有加到后面
s = temp;
}
cout << s;
}
双指针法
@不了解可以看这篇:双指针法
#include<iostream>
#include<string>
using namespace std;
int main() {
string s; int n;
cin >> s >> n;
while (--n) {
string temp;
int i, j;
for (i = 0; i < s.size(); i=j) {
for (j = i; j < s.size()&&s[i]==s[j]; j++);
temp += s[i]; temp += j - i + '0';
}
s = temp;
}
cout << s;
return 0;
}
对比总结
相比之下,同样的思路,用双指针法解题更简洁,而在线处理却还有一些细节需要考虑。