Encoding
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1020
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 55038 Accepted Submission(s):
24576
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
Author
ZHANG Zheng
可以用暴力求解法求解。
JAVA代码如下:
import java.util.Scanner; public class Main { public static void main(String[] args) { @SuppressWarnings("resource") Scanner inScanner = new Scanner(System.in); int num = inScanner.nextInt(); inScanner.nextLine(); while(num-->0) { String string = inScanner.nextLine(); string+="a";//这个要注意,防止接下来的统计时会有溢出的。 int sum = 1; for(int i = 0;i < string.length()-1;i++) { if(string.charAt(i) == string.charAt(i+1)) {
sum++; } else { if(sum==1) { System.out.print(string.charAt(i)); } else { System.out.print(sum + "" + string.charAt(i)); sum = 1; } } } System.out.println();//这个很迷,我之前由于用了String.out.print(" ");而WA了好几次。。。。。。
} } }
C++代码:
#include<iostream> #include<string> using namespace std; int main() { int t; cin>>t; while(t--) { string a; cin>>a; int len=a.length(); int sum=1; for(int i=0;i<len;i++) { if(a[i]==a[i+1]) { sum++; } else { if(sum==1) { cout<<a[i]; sum=1; } else { cout<<sum<<a[i]; sum=1; } } } cout<<endl; } return 0; }