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问题描述与算法分析
题目的意思是当字符串存在多个相同的字符时,在每个字符前加上该字符在字符串中出现的次数。若不存在相同的字符,则只输出字符串。基本思路:① 构造一个字符串数组,初始化相同字符的数量num为1,把数组的第一个值str[0]赋值给临时变量temp;② 从数组的第二个元素查找,若存在与temp值相同的字符,则执行num++,否则转向③ 若num的值不为1,表明数组存在与str[0]相同的字符,打印出num和temp;若num的值为1,表明数组中str[0]对应的字符只有一个,直接打印出temp;将num值重置为1,temp值赋值为str[i],作为下一次循环的初始条件。代码如下
#include <iostream> #include <string> using namespace std; int main() { string str; int i,j; int N; cin>>N; while(N--) { cin>>str; int num=1;//用于统计字符个数 char t=str[0];//临时变量,用于判断数组是否有相同的字符 for(i=1;i<=str.length();i++) { if(str[i]==t) num++; else { if(num!=1) { cout<<num<<t; } else { cout<<t; } //num和t重新赋值,作为下一次循环初始条件 num=1; t=str[i]; } } cout<<endl; } return 0; }
测试结果截图