Encoding
Problem Description
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.
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.
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
/*
*只要求统计连续相同的字符,有个误区,这里不是求一个字符串中所有相同的字符,
*
*运算思想:
*
* 通过for循环统计相邻的字符,如果后一个字符和前一个字符相同则对应的数值为前一个字符数值加1
* 同时前一个字符赋值‘-1’,避免重复输出,因为数值默认为0,所以只要在长度内有0说明此处存在一个字符
* 如果数值为‘-1’说明此处字符已被统计在后面,不要输出。
*
*
2
ABC
ABBCCC
*
ABC
A2B3C
*
*输入运算次数n,输入字符串,统计出相邻字符串,数量为1时‘1’不显示
*
*/
#include<iostream>
using namespace std;
int main()
{
//input负责接收输入的字符串,根据题目要求,字符串长度不超过10000
char input[10000];
//n负责接收所需进行的运算次数,lenth里存储所输入字符串的长度,i、k,为方便运算的变量
int n,lenth,i,k;
//number数组负责存储相邻字符出现的次数
int number[10000];
//输入所需进行的运算次数,通过while实现循环
cin>>n;
while(n)
{
//memset函数是以字节为单位对number数组清零处理
memset(number,0,sizeof(number));
//输入数组
cin>>input;
//通过strlen函数,让lenth获取到所输入的数组的长度
lenth=strlen(input);
//通过for循环统计相邻的字符,如果后一个字符和前一个字符相同则对应的数值为前一个字符数值加1
//同时前一个字符赋值‘-1’,避免重复输出,因为数值默认为0,所以只要在长度内有0说明此处存在一个字符
//如果数值为‘-1’说明此处字符已被统计在后面,不要输出。
for(i=1;i<lenth;i++)
{
if(input[i]==input[i-1])
{
number[i]=number[i-1]+1;
number[i-1]=-1;
}
}
//当字符对应数值处为0时说明周围只存在这一个字符,按照题目要求不用输出‘1’直接输出对应字符即可
for(i=0;i<lenth;i++)
{
if(number[i]==0)
{
cout<<input[i];
}
//此处注意使用else if而不是else因为存在已记录过的字符对用数值为-1的情况
else if(number[i]>0)
{
cout<<number[i]+1<<input[i];
}
}
cout<<endl;
//每循环一次需进行的运算次数减1,保证while循环的正确性
n--;
}
return 0;
}