0451.cpp (863B)
1 class Solution { 2 public: 3 string frequencySort(string &s) const { 4 unordered_map<char, int> freq; 5 vector<string> bucket(size(s) + 1); 6 7 for (char c : s) 8 freq[c]++; 9 for (auto [c, n] : freq) 10 bucket[n].append(n, c); 11 12 string res; 13 for (int i = s.size(); i > 0; i--) { 14 if (!bucket[i].empty()) res.append(bucket[i]); 15 } 16 17 return res; 18 } 19 }; 20 21 class Solution { 22 public: 23 string frequencySort(const string &s) const { 24 static pair<int, char> count[128]; 25 26 for (int i = 0; i < size(count); i++) 27 count[i] = {0, i}; 28 for (const char c : s) 29 count[c].first++; 30 sort(rbegin(count), rend(count)); 31 32 string res; 33 for (const auto [n, c] : count) 34 res += string(n, c); 35 36 return res; 37 } 38 };