【50】451. Sort Characters By Frequency
451. Sort Characters By Frequency
Description Submission Solutions Add to List
- Total Accepted: 17072
- Total Submissions: 34068
- Difficulty: Medium
- Contributors: stickypens
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
1 class Solution { 2 public: 3 string frequencySort(string s) { 4 string res = ""; 5 unordered_map<char, int> hash;//用来记录谁出现了几次 6 priority_queue<pair<int, char>> q;//用来直接排序,把map的两个值反过来记录 7 for(char c : s){ 8 hash[c]++; 9 } 10 for(auto a : hash){ 11 q.push(make_pair(a.second, a.first)); 12 } 13 while(!q.empty()){ 14 auto top = q.top(); 15 q.pop(); 16 // string& append (size_t n, char c); 17 //Appends n consecutive copies of character c. 18 res.append(top.first, top.second);//把谁append,加上几次 19 } 20 return res; 21 } 22 };