1. 题目
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
输入:
"tree"输出:
"eert"
2. 优先队列解题
- 先用map统计字符出现次数
- 再将字符何其次数插入优先队列
- 出队
struct cmp
{ //写在类内也可以,写在函数里也行bool operator()(pair<char,int> &a, pair<char,int> &b){return a.second < b.second;}
};
class Solution {
public:string frequencySort(string s) {map<char,int> m;priority_queue<pair<char,int>, vector<pair<char,int>>, cmp> q;string ans;int n;for(int i = 0; i < s.size(); ++i)m[s[i]]++;for(auto it = m.begin(); it != m.end(); ++it){q.push(*it);}while(!q.empty()){n = q.top().second;while(n--)ans.push_back(q.top().first);q.pop();}return ans;}
};