hdu 1020 Encoding

Encoding

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 40214    Accepted Submission(s): 17846


ios

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

 分析:有兩種比較方式。第一種是s[i]與s[i+1]比較,當與s[i+1]不一樣時,則按要求輸出s[i],這裏若是是定義string s,less

最後s[s.length() - 1]和s[s.length()]比較會報錯(用的是VS2010),因此我定義成char s[10001],最後s[strlen[s] - 1]和s[strlen[s]] = '\0'比較沒有報錯。this

 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]相不相等,都不會輸出最後一個相同的字符字串。spa

 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 }
相關文章
相關標籤/搜索