【LeetCode】Hash
[451] Sort Characters By Frequency [Medium]
给一个字符串,要求返回按照字母出现频率的排序后的字符串。(哈希表+桶排)
有个技巧是Hash用Value作为Index放到桶里。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 string frequencySort(string s) { 4 map<char, int> mp; 5 for (auto c : s) { 6 mp[c]++; 7 } 8 string ans = ""; 9 // 桶排序 10 vector<string> bucket(s.size()+1, ""); 11 for (auto ele : mp) { 12 char ch = ele.first; 13 int cnt = ele.second; 14 bucket[cnt].append(cnt, ch); 15 } 16 for (auto i = bucket.size() - 1; i >= 1; --i) { 17 ans += bucket[i]; 18 } 19 return ans; 20 } 21 };