Simple C++ Solution


  • 0
    B
    class Solution {
    public:
        string frequencySort(string s) {
            // part 1 : count characters
            unordered_map<char,int> M;
            for (char ch : s)
                M[ch]++;
    
            // part 2 : sort characters by frequency
            vector<pair<int,char>> V;
            for (auto it : M)
                V.emplace_back(-it.second, it.first);
            sort(V.begin(), V.end());
    
            // part 3 : make a string
            string res;
            for (auto it : V)
                res.append(-it.first, it.second);
            
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.