Encoding
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 40214 Accepted Submission(s): 17846
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
分析:有两种比较方式。第一种是s[i]与s[i+1]比较,当与s[i+1]不同时,则按要求输出s[i],这里如果是定义string s,
最后s[s.length() - 1]和s[s.length()]比较会报错(用的是VS2010),所以我定义成char s[10001],最后s[strlen[s] - 1]和s[strlen[s]] = '\0'比较没有报错。
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 int main(){ 5 int n; 6 char s[10001]; 7 cin >> n; 8 while(n--){ 9 cin >> s; 10 int num = 1; 11 int len = strlen(s); 12 for(int i = 0; i < len; i++){ 13 if(s[i] == s[i+1]) 14 num++; 15 else { 16 if(num == 1){ 17 cout << s[i]; 18 } else { 19 cout << num << s[i]; 20 num = 1; 21 } 22 } 23 } 24 cout << endl; 25 } 26 return 0; 27 }
第二种比较方法则是从下标1开始,s[i]和s[i-1]比较。当s[i] != s[i-1],则按要求输出s[i-1]。注意:不管s[s.length()-1]和s[s.length()-2]相不相等,都不会输出最后一个相同的字符字串。
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 int main(){ 5 int n; 6 string s; 7 cin >> n; 8 while(n--){ 9 cin >> s; 10 int num = 1; 11 int len = s.length(); 12 for(int i = 1; i < len; i++){ 13 if(s[i - 1] == s[i]){ 14 num++; 15 } else { 16 if(num != 1){ 17 cout << num << s[i - 1]; 18 num = 1; 19 } 20 else { 21 cout << s[i - 1]; 22 } 23 } 24 } 25 if(num != 1) 26 cout << num << s[len - 1]; 27 else 28 cout << s[len - 1]; 29 cout << endl; 30 } 31 return 0; 32 }