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
Title description:
Given a string containing only'A'-'Z', we can use the following methods to encode it:
1. Each substring containing k identical characters should be encoded as "kX", where "X" is the only character-string in the subelement.
2. If the length of the substring is 1, then '1' should be ignored.
Problem-solving idea: The
problem only requires counting consecutive identical characters, not all identical characters in a string. For
example:
AAABBCCAA
3A2B2C2A
Traverse the string and add 1 if the current character is the same as the next character.
#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;
}