solution1
- 测试点3是n==1的情况
- int转string:str = to_string(i)
string转int:i = atoi(str.c_str())
#include<iostream>
#include<string>
using namespace std;
int main(){
int n, cnt;
char x;
string ans, t;
cin >> t >> n;
for(int i = 2; i <= n; i++){
ans = t[0];
x = t[0];
cnt = 1;
for(int i = 1; i < t.size(); i++){
if(x == t[i]) cnt++;
else{
ans += to_string(cnt) + t[i];
x = t[i];
cnt = 1;
}
}
ans += to_string(cnt);
t = ans;
}
if(n == 1) cout << t;
else cout << ans;
return 0;
}
或者
#include<iostream>
#include<string>
using namespace std;
int main(){
int n, cnt;
char x;
string ans, t;
cin >> t >> n;
for(int i = 2; i <= n; i++){
ans = t[0];
x = t[0];
cnt = 1;
for(int i = 1; i < t.size(); i++){
if(x == t[i]) cnt++;
else{
ans += to_string(cnt) + t[i];
x = t[i];
cnt = 1;
}
}
ans += to_string(cnt);
t = ans;
}
cout << t;
return 0;
}
solution2
优雅
#include<iostream>
#include<string>
using namespace std;
int main(){
int n, k;
string ans, t;
cin >> t >> n;
for(int i = 1; i < n; i++){
ans = "";
for(int j = 0; j < t.size(); j = k){
for(k = j; j < t.size() && t[j] == t[k]; k++);
ans += t[j] + to_string(k - j);
}
t = ans;
}
cout << t;
return 0;
}