题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(const pair<char,int>& a, const pair<char,int>& b){
// 返回true代表第一个形参在前面
if(a.second == b.second){
return a.first < b.first;
}else{
return a.second > b.second;
}
}
int main() {
string s;
map<char,int> m1;
cin >> s;
int n = s.size();
for(int i=0; i<n; i++){
if(m1.find(s[i]) == m1.end()){
m1[s[i]] = 1;
}else{
m1[s[i]]++;
}
}
vector<pair<char,int>> res(m1.begin(),m1.end());
sort(res.begin(),res.end(),cmp);
for(auto& i:res){
cout << i.first;
}
cout << endl;
return 0;
}
// 64 位输出请用 printf("%lld")
本题的知识点在于通过自定义cmp和sort函数的配合起到自定义顺序的效果,需要特别注意的是sort一般是配合vector容器使用的,所以有一个容器转换的过程。

快手公司福利 1244人发布