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.
Input
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.
Output
For each test case, output the encoded string in a line.
Sample Input
2
ABC
ABBCCC
Sample Output
ABC
A2B3C
题意描述:
给定一个仅包含’A’-'Z’的字符串,我们可以使用以下方法对其进行编码:
1.每个包含k个相同字符的子字符串应编码为“ kX”,其中“ X”是该子元素中的唯一字符-串。
2.如果子字符串的长度为1,则应忽略’1’。
解题思路:
题目只要求统计连续相同的字符,而不是一个字符串中所有相同的字符
如:
AAABBCCAA
3A2B2C2A
对字符串进行遍历,如果当前的字符与后一个的字符相同的话加1。
#include <stdio.h>
#include <string.h>
int main()
{
int n,i,sum;
char str[10001];
scanf("%d",&n);
while(n--)
{
scanf("%s",str);
sum=1;
int l=strlen(str);
for(i=0;i<l;i++)
{
if(str[i]==str[i+1])
{
sum++;
}
else
{
if(sum==1)
{
printf("%c",str[i]);
sum=1;
}
else
{
printf("%d%c",sum,str[i]);
sum=1;
}
}
}
printf("\n");
}
return 0;
}