给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
示例 1:
输入:
"tree"
输出:
"eert"
解释:
'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。
示例 2:
输入:
"cccaaa"
输出:
"cccaaa"
解释:
'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。
注意"cacaca"是不正确的,因为相同的字母必须放在一起。
示例 3:
输入:
"Aabb"
输出:
"bbAa"
解释:
此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。
注意'A'和'a'被认为是两种不同的字符。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-characters-by-frequency
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1 #include<bits/stdc++.h> 2 using namespace std; 3 //优先队列 大顶堆实现 90% 4 class Solution { 5 public: 6 struct Cell 7 { 8 char c; 9 int frequency; 10 Cell(char ch, int freq):c(ch), frequency(freq) {}; 11 friend bool operator <(Cell c1, Cell c2) 12 { 13 if (c1.frequency == c2.frequency) 14 return c1.c > c2.c; 15 else 16 return c1.frequency < c2.frequency; 17 } 18 }; 19 string frequencySort(string s) { 20 map<char, int> hash; 21 priority_queue<Cell> que; 22 int len = s.length(); 23 for (int i = 0; i < len; i++) 24 hash[s[i]]++; 25 for (auto item : hash) 26 que.push({ item.first, item.second }); 27 string res = ""; 28 while (!que.empty()) 29 { 30 auto p = que.top(); 31 que.pop(); 32 for (int i = 0; i < p.frequency; i++) 33 res += p.c; 34 } 35 return res; 36 } 37 }; 38 int main() 39 { 40 string s; 41 cin >> s; 42 cout << Solution().frequencySort(s); 43 return 0; 44 }