题目描述
输入一个只包含小写英文字母和数字的字符串,按照不同字符统计个数由多到少输出统计结果,如果统计的个数相同,则按照ASCII码由小到大排序输出。
本题含有多组样例输入
输入描述:
一个只包含小写英文字母和数字的字符串。
输出描述:
一个字符串,为不同字母出现次数的降序表示。若出现次数相同,则按ASCII码的升序输出。
示例1
输入
aaddccdc
1b1bbbbbbbbb
输出
cda
b1
说明
第一个样例里,c和d出现3次,a出现2次,但c的ASCII码比d小,所以先输出c,再输出d,最后输出a.
C++解法:
#include <iostream>
#include <string>
#include <cstring>
#include <map>
#include <vector>
#include <set>
using namespace std;
int main()
{
string input;
while (getline(cin, input)) {
map<char, int> results;
map<int, set<char>> maxResults;
int length = input.length();
for (int i = 0; i < length; i++) {
char single = input.at(i);
if (results.find(single) != results.end()) {
results[single]++;
}
else {
results[single] = 1;
}
}
map<char, int>::const_iterator cit = results.cbegin();
for (; cit != results.end(); cit++) {
if (maxResults.find(cit->second) != maxResults.end()) {
maxResults[cit->second].insert(cit->first);
}
else {
set<char> chars;
chars.insert(cit->first);
maxResults[cit->second] = chars;
}
}
// map自动升序排序的
map<int, set<char>>::const_reverse_iterator scit = maxResults.crbegin();
for (; scit != maxResults.crend(); scit++) {
set<char>::const_iterator charCit = scit->second.cbegin();
for (; charCit != scit->second.cend(); charCit++) {
cout << *charCit;
}
}
cout << endl;
}
return 0;
}