题目链接
代码中有注释;
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
#pragma warning(disable:4996);
#include <iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<stack>
using namespace std;
int main()
{
string a;//string,可以方便地进行字符串拼接;
int n;
cin >> a >> n;
for (int j = 1;j < n;j++)//最开始给的已经是第一项了,所以j=1,而不是从0,否则会多循环一次;
{
string ans;
int cnt = 0;//统计出现相同字符的个数;
char c = a[0];//从第一个开始;
for (int i = 0;i < a.length();i++)
{
if (a[i] == c)cnt++;
else {
ans += c;//字符放入字符串中;
ans += cnt + '0';//放入对应个数;
c = a[i];//从不相等的字符开始循环;
cnt = 1;//因为这个a[i]不会被判断相等而是直接做i++,所以计数器直接放一;
}
}
if (cnt > 0) {//因为到最后一个字符,如果cnt还有值,那么就要对最后一个字符进行操作,可能是最后一个字符与倒数第二个不想等导致,也有可能是连续几个字符相等导致,所以要对最后一个情况进行处理;
ans += c;
ans += cnt + '0';
}
a = ans;//因为每次都从a中取,所以要把每次更新的新字符串交给a;
}
cout << a << endl;
return 0;
}