map初步(由ABBC--->A2BC)
1.题目:
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.
InputThe 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.
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.
OutputFor each test case, output the encoded string in a line.
Sample Input
2 ABC ABBCCCSample Output
ABC A2B3C
2.代码:
//本题使用G++编译 #include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--){ int sum=1; string a;//定义字符数组 cin>>a;//输入字符数组内容 for(int i=0;i<a.length();i++){ if(a[i]==a[i+1]) sum++;//若相邻两个字符相同则sum+1 else//若相邻字符不相同则进行else { if(sum!=1)//若sum!=1,即相邻字符相同则输出sum再输出字符 cout<<sum<<a[i]; else//若相邻字符不相同则直接输出字符 cout<<a[i]; sum=1; } } cout<<endl; } }
3.总结:
应用了map算法!!!