2013
11-28

# Encoding

Given a string containing only ‘A’ – ‘Z’, we could encode it using the following method:

1. Each sub-string containing k same characters should be encoded to "kX" where "X" is the only character in this sub-string.

2. 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

#include <iostream>
using namespace std ;
int main()
{
int t,i,num ;
char a[10002];

scanf("%d%*c",&t);
while(t--)
{
gets(a);

num=1 ;
for(i=0;a[i]!='/0';i++)
{
if(a[i]==a[i+1])
num++;
if(a[i]!=a[i+1]||a[i+1]=='/0')
{
if(num==1)
printf("%c",a[i]);
else
printf("%d%c",num,a[i]);
num=1 ;
}
}
printf("/n");
}
return 0 ;
}

1. 思路二可以用一个长度为k的队列来实现，入队后判断下队尾元素的next指针是否为空，若为空，则出队指针即为所求。