Straight forward C++ answer

  • 0

    The method is very simple:

    1. Insert all the letters into an unordered map.
    2. Use set to sort the letters via frequency.
    3. Insert the letters into the answer string.
    string frequencySort(string s) {
            string ans;
            // The key is letter and the val is the frequency
            unordered_map<char, int> mp; 
            for(char c : s)
            set<pair<int,char>> p;
            for(auto m : mp)
                p.insert(make_pair(m.second, m.first));
            for(auto i : p){
                //Repeat n times when insert the letter into the answer string
                for(int n = 0; n < i.first; n++)
                    ans.insert(ans.begin(), 1, i.second);
            return ans;

Log in to reply

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