原题链接:Problem - 1020
题目描述
Given a string containing only ‘A’ - ‘Z’, we could encode it using the following method:
-
Each sub-string containing k same characters should be encoded to “kX” where “X” is the only character in this sub-string.
-
If the length of the sub-string is 1, ‘1’ should be ignored.
输入格式
The first line contains an integer N (1 <= N <= 100) which indicates the number of test cases. The next N lines contain N strings. Each string consists of only ‘A’ - ‘Z’ and the length is less than 10000.
输出格式
For each test case, output the encoded string in a line.
输入样例
2
ABC
ABBCCC
输出样例
ABC
A2B3C
题意
给定一个仅包含 'A'-'Z'
的字符串,使用以下方法对其进行编码:
-
包含 k 个相同字符的每个子串都编码为
"kX"
,其中"X"
是该子串中的唯一字符。
比如AAABBB
将编码成3A3B
,而ABABAB
编码后仍然是ABABAB
。 -
如果子串的长度为 1,则忽略
'1'
。
样例解释
以 ABBCCC
为例,A
编码成 A
('1'
被忽略),BB
编码成 2B
,CCC
编码成 3C
。
解题思路
遍历字符串,对每一个字符计算它后面有多少个相同的字符,并记录下来。
输出字符串时,如果当前字符后面有相同的字符,需要输出相同字符的数量,并跳过后面一系列相同的字符。
程序代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
getchar();
string s;
int a[10000];
while(n--)
{
getline(cin, s);
memset(a, 0, sizeof(a));
for(int i = 0; i < s.size();)
{
a[i]++;
if(i != s.size() - 1)
{
for(int j = i + 1; j < s.size(); j++)
{
if(s[i] != s[j]) break;
a[i]++;
}
}
else
a[i] = 1;
i += a[i];
}
for(int i = 0; i < s.size();)
{
if(a[i] > 1)
printf("%d", a[i]);
putchar(s[i]);
i += a[i];
}
putchar('\n');
}
return 0;
}