- 根据字符出现频率排序
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
class Solution {
public:
bool static 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;
}
string frequencySort(string s) {
map<char, int> mp;
for (char ch : s) {
mp[ch]++;
}
vector<pair<char, int>> vec(mp.begin(), mp.end());
sort(vec.begin(), vec.end(), cmp);
string res;
for (int i = 0; i < vec.size(); i++) {
for (int j = 0; j < vec[i].second; j++) {
res += vec[i].first;
}
}
return res;
}
};