Straightforward C++ Solution


  • 0
    G
        string frequencySort(string s) {
            unordered_map<char, int> cf; // character frequency
            for (int i = 0; i < s.size(); i++) {
                cf[s[i]]++;
            }
            multimap<int, char> fc; // frequency to characters
            for (unordered_map<char, int>::iterator it = cf.begin(); it != cf.end(); it++) {
                pair<int, char> p(it->second, it->first);
                fc.insert(p);
            }
            string r("");
            for (multimap<int, char>::reverse_iterator it = fc.rbegin(); it != fc.rend(); it++) {
                for (int i = 0; i < it->first; i++) {
                    r.push_back(it->second);
                }
            }
            return r;
        }
    

Log in to reply
 

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