首页 > 代码库 > hdu 1020 Encoding
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
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 else28 cout << s[len - 1];29 cout << endl;30 }31 return 0;32 }
hdu 1020 Encoding
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。