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.
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
分析:从头扫一遍字符串,统计每个连续的字母序列有多少个,然后边统计边输出。
1 #include <cstdio> 2 #include <cmath> 3 #include <cstring> 4 #include <ctime> 5 #include <iostream> 6 #include <algorithm> 7 #include <set> 8 #include <vector> 9 #include <sstream> 10 #include <queue> 11 #include <typeinfo> 12 #include <fstream> 13 #include <map> 14 #include <stack> 15 using namespace std; 16 #define INF 100000 17 typedef long long ll; 18 const int maxn=10010; 19 char s[maxn]; 20 int main() 21 { 22 int n; 23 scanf("%d",&n); 24 while(n--){ 25 scanf("%s",s); 26 int temp=1; 27 for(int i=1;i<=strlen(s);i++){ 28 if(s[i]==s[i-1]) temp++; 29 else{ 30 if(temp==1) printf("%c",s[i-1]); 31 else printf("%d%c",temp,s[i-1]); 32 temp=1; 33 } 34 } 35 printf("\n"); 36 } 37 return 0; 38 }
时间: 2024-10-31 02:55:42