Easy C++ solution using Map and Unordered Map to take care of orders.


  • 1
    Z
    1. Use a unordered_map<char,int> to count the frequency of each char. The reason of using unordered_map instead of map is because unordered_map keeps the original order of characters in string.
    2. Use a map<int,vector<char>> to record the characters' frequency. The reason of using map instead of unordered_map is because map can sort the key automatically.

    string frequencySort(string s) {

        string res;
        unordered_map<char,int> freq;
        map<int,vector<char>> mfreq;
        
        for(auto c : s) freq[c]++;
        for(auto x : freq) mfreq[x.second].push_back(x.first);
        
        for(auto it = mfreq.rbegin(); it != mfreq.rend(); it++){
            for(auto c : it->second){
                res.append(it->first,c);
            }
        } 
        
        return res;
    }

  • 0
    K

    @zalbert said in Easy C++ solution using Map and Unordered Map to take care of orders.:

    map<int,vector<char>> mfreq;

    why not map<int,char> mfreq ?


  • 0
    Z

    @kupe Different characters might have the same frequency, vector<char> is used to records all the chatterers, keeping them in the original order as well.


  • 0
    K

    @zalbert THX good solution


Log in to reply
 

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