字符统计及重排
标题:字符统计及重排 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
给出一个仅包含字母的字符串,不包含空格,统计字符串中各个字母(区分大小写)出现的次数,并按照字母出现次数从大到小的顺序输出各个字母及其出现次数。如果次数相同,按照自然顺序进行排序,且小写字母在大写字母之前。
#include <bits/stdc++.h>
using namespace std;
typedef struct{
char ch;
int value;
}node;
int s1[26],s2[26];
bool cmp(node a,node b) {
if(a.value == b.value) {
if(islower(a.ch) && islower(b.ch)) {
return a.ch < b.ch;
}
if(isupper(a.ch) && isupper(b.ch)) {
return a.ch < b.ch;
}
if(islower(a.ch)) {
return true;
} else {
return false;
}
}
return a.value > b.value;
}
int main(void)
{
string str;
while(cin >> str) {
memset(s1,0,26 * sizeof(int));
memset(s1,0,26 * sizeof(int));
for(int i=0;i<(int)str.size();i++) {
if(islower(str[i])) {
s1[str[i] - 'a'] += 1;
} else {
s2[str[i] - 'A'] += 1;
}
}
vector<node> ans;
for(int i=0;i<26;i++) {
if(s1[i] != 0) {
node t;
t.ch = i + 'a';
t.value = s1[i];
ans.push_back(t);
}
if(s2[i] != 0) {
node t;
t.ch = i + 'A';
t.value = s2[i];
ans.push_back(t);
}
}
sort(ans.begin(),ans.end(),cmp);
for(int i=0;i<ans.size();i++) {
cout << ans[i].ch << ":" << ans[i].value << ';';
}
}
return 0;
}