写在前面
- 理解题意耗费些时间
- 没有太好的解法。Step1,弄懂题意;Step2厘清逻辑
- 遍历字符串,计算外观数列,并更新下一迭代数列字符串。
- 迭代字符串
- 更换数列值
- 判断字符串遍历结束,更新最新下标值(k)
- to_string等函数,思路略显臃肿。有更优方法
测试用例
input:
1 8
output:
1123123111
compute process:
1
11
12
1121
122111
112213
12221131
1123123111
ac代码
#include<string>
#include<iostream>
using namespace std;
int main()
{
int d, n;
scanf("%d%d", &d, &n);
int cnt = 0;
string src_ds, result_ds, cur_ds;
src_ds = to_string(d);
for(int i=1; i<n; i++)
{
for(int k=0; k<src_ds.length(); k++)
{
cur_ds = src_ds.substr(k,1);
for(int j=k; j<src_ds.length(); j++)
{
if(cur_ds == src_ds.substr(j,1)) cnt++;
else break;
}
k += cnt-1;
result_ds += (cur_ds + to_string(cnt));
cnt = 0;
}
src_ds = result_ds;
result_ds = "";
}
cout << src_ds << endl;
return 0;
}
参考代码
#include <iostream>
using namespace std;
int main() {
string s;
int n, j;
cin >> s >> n;
for (int cnt = 1; cnt < n; cnt++) {
string t;
for (int i = 0; i < s.length(); i = j) {
for (j = i; j < s.length() && s[j] == s[i]; j++);
t += s[i] + to_string(j - i);
}
s = t;
}
cout << s;
return 0;
}