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 100. Output For each test case, output the encoded string in a line. Sample Input 2 ABC ABBCCC Sample Output ABC A2B3C 来自:http://acm.zju.edu.cn/ 2478 |
[技术| 编程·课件·Linux] ACM趣题天天练 6 Encoding
simon3322
· 发布于 2012-09-04 09:42
· 1150 次阅读
转载文章时务必注明原作者及原始链接,并注明「发表于 软院网 RuanYuan.Net 」,并不得对作品进行修改。
[C++] 纯文本查看 复制代码 #include <iostream> #include <string> using namespace std; int main() { int n,i,len,k; string str; char tmp; while(cin >> n) { while(n--) { cin >> str; len = str.length(); for(i = 0; i < len; ++i) { tmp = str[i]; k = 1; while(str[++i] == tmp) { k++; } if(k != 1) { cout << k; } cout << tmp; i--; } cout << endl; } } return 0; } |
评分
[Java] 纯文本查看 复制代码 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); while (n-- > 0) { int count; char temp; String str = sc.nextLine(); for (int i = 0; i < str.length(); i++) { count = 0; temp = str.charAt(i); while (i < str.length() && str.charAt(i) == temp) { count++; i++; } if (count > 1) { System.out.print(count); } System.out.print(temp); i--; } System.out.println(); } sc.close(); } } |