leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0451.cpp (863B)


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