leetcode 451. 根据字符出现频率排序 medium
题目描述:
解题思路:
hash表统计词频+ 桶排(堆排也可)
代码:
//
class Solution {
public:
string frequencySort(string s) {
int max_cnt = 0;
unordered_map<char, int> hash;
for (char &c: s){
hash[c]++;
max_cnt = max(max_cnt, hash[c]);
}
vector<vector<char>> buckets(max_cnt+1);
for (auto &p: hash){
buckets[p.second].push_back(p.first);
}
string res;
for (int i = max_cnt; i >= 0; i--){
for (char c: buckets[i])
res += string(i, c);
}
return res;
}
};