根据字符出现频率排序(STL)
思路
哈希存储每个字符出现的个数,利用pair+优先队列的特性,以pair的第一关键字降序,第二关键字降序的顺序放入优先队列中的
class Solution {
public:
typedef pair<int, char> PIC;
string frequencySort(string s) {
unordered_map<char, int> hash;
for (auto &c : s)
hash[c] ++;
string res;
priority_queue<PIC> heap;
for (auto &t : hash)
{
char c = t.first;
int k = t.second;
heap.push({k, c});
}
while (heap.size())
{
auto [v, c] = heap.top();
heap.pop();
while (v -- ) res += c;
}
return res;
}
};