总体思路:与347思路类似都是使用桶排序。先用哈希表记录每个字母出现的频率;第二步使用vevtor模拟桶,频率作为桶的下标,桶里面填充相应频率的字母;最后按照减序遍历往结果数组中添加字母即可。
class Solution {
public:
string frequencySort(string s) {
unordered_map<char, int> counts;
int max_count = 0;
for (const auto & iter : s) {
max_count = max(max_count, ++counts[iter]);
}
vector<vector<char>> buckets(max_count + 1);
for (const auto & t : counts) {
buckets[t.second].push_back(t.first);
}
string res;
for (int i = max_count; i >= 0; i--) {
for (auto p : buckets[i]) {
auto temp = i;
while (temp != 0) {
temp--;
res += p;
}
}
}
return res;
}
};