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
这题一开始我理解错了意思,以为是把所有的字母从小到大排好序来算的,用map错了
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int T;
cin >> T;
while (T--) {
string s;
s.clear();
cin >> s;
map<char, int>mp;
mp.clear();
for (int i = 0;s[i];i++) {
mp[s[i]]++;
}
map<char, int>::iterator it;
for (it = mp.begin();it != mp.end();++it) {
if (it->second == 1)cout << it->first;
else cout << it->second << it->first;
}
cout << endl;
}
return 0;
}
AC代码
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<iostream>
using namespace std;
char s[10005];
int main()
{
int T;
cin>>T;
while (T--) {
int flag = 1;
cin>>s;
int len = strlen(s);
for (int i = 0;i<len;i++)
{
if (s[i] == s[i + 1])
flag++;
else {
if (flag>1)
cout<<flag;
cout<<s[i];
flag = 1;
}
}
cout << endl;;
}
return 0;
}