1、描述
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
示例 1:
输入:
“tree”
输出:
“eert”
解释:
'e’出现两次,'r’和’t’都只出现一次。
因此’e’必须出现在’r’和’t’之前。此外,"eetr"也是一个有效的答案。
来源:力扣(LeetCode)
链接:
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、关键字&思路
字符频次,-----> hash_map统计
排序-------> 优先队列,大根堆,然后全部进堆,从顶开始弹出,就行了
4、notes
最后字符串叠加的时候,需要根据出现的次数累加次数遍
5、复杂度
时间:(O(n+klogk),n是字符串长度,k是不同字符的个数
空间:O(N + k)
6、code
typedef pair<char,int>pii;
struct cmp{
bool operator()(pii a,pii b){ // 大根堆的比较器,
return a.second < b.second;
}
};
class Solution {
public:
string frequencySort(string s) {
unordered_map<char,int>mp;
for(auto c:s){ // 构造hash_map,
mp[c]++;
}
string res;
priority_queue<pii,vector<pii>,cmp> heap; // 搞一个大根堆,
for(auto tem : mp){
heap.push(tem);
}
while(!heap.empty()){
auto c = heap.top().first;
int num = heap.top().second;
while(num--){ // 累加的次数,
res += c;
}
heap.pop();
}
return res;
}
};