题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(const pair<char, int> & a, const pair<char, int> & b) {
if(a.second == b.second){
return a.first < b.first;
}
return a.second > b.second;
}
struct cmp1{
bool operator()(const pair<char, int> & a, const pair<char, int> & b){
if(a.second == b.second){
return a.first < b.first;
}
return a.second > b.second;
}
};
int main(){
string s = "";
while(getline(cin, s)){
map<char, int> m;
for(char ch : s){
m[ch]++;
}
vector<pair<char, int>> v(m.begin(), m.end()); //
//sort(v.begin(), v.end(), cmp;
//stable_sort(v.begin(), v.end(), cmp1());
//因为map已经依照键排序了,所以用稳定排序当次数一样时,会保持原来的先后关系,即ASCII码的升序
stable_sort(v.begin(), v.end(), [](const pair<char,int>& a,const pair<char,int>& b){
//用Lambda来写配合算法使用的小函数是非常方便的
return a.second>b.second;
});
for(auto iter : v){
cout << iter.first;
}
cout << endl;
}
return 0;
}
华为题库题解 文章被收录于专栏
牛客华为题库的题解
