Naive C++ solution with map/multimap


  • 0
    C

    Better runtime than brute sorting

    class Solution {
    public:
        string frequencySort(string s) {
            unordered_map<char, int> mp;
            multimap<int, char, greater<int>> smp;
            for(auto ch : s)
                mp[ch]++;
            for(auto it : mp)
                smp.insert(make_pair(it.second, it.first));
           
            string ret;
            for(auto it = smp.begin(); it != smp.end(); ++it)
                ret += string(it->first, it->second);
            return ret;
        }
    };
    

Log in to reply
 

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