此题与LeetCode347是基本一样的
对于这种频率统计并排序问题,做法一:桶排序的套娃
做法二:map+堆
做法二更不容易错一些,而且非常通用,故记录写法。
map的建立为 <字母,对应的频率>, c++优先队列自动安装key值进行调整,所以push的时候要反过来。
写法参考如下:
class Solution {
public:
string frequencySort(string s) {
unordered_map<char,int> fre;
for(char ch:s)
{
fre[ch]++;
}
priority_queue<pair<int,char>> q;
for(auto f:fre)
{
q.push({f.second,f.first});
}
string res="";
while(!q.empty())
{
for(int i=0;i<q.top().first;i++)
{
res+=q.top().second;
}
q.pop();
}
return res;
}
};