解决上述问题,需要思考两个问题:
1、如何统计string字符串中的每个字符出现的频率;
2、如何按照字符出现的频率从高到底的输出每个字符。
以下是解决上述问题的两个方法:
1、使用hash_map哈希表来统计每个字符出现的频率;2、使用最大优先队列将字符出现的频率依次入队,并排序。
class Solution {
public:
string frequencySort(string s) {
string res="";
unordered_map<char,int> hash; //记录每个字符出现的次数
priority_queue<pair<int,char>> que; //优先队列对字符出现的频率进行排序,并将两个值反过来
//统计每个字符出现的频率
for(char ch:s){
hash[ch]++;
}
//将每一个字符按照出现的频率加入到队列中去
for(auto ha:hash){
que.push(make_pair(ha.second,ha.first));
}
//循环取出队列中的字符和字符的频率
while(!que.empty()){
auto top=que.top();
que.pop();
res.append(top.first,top.second);
}
return res;
}
};