Concise priority queue solution, O(n logn)


  • 0
    M
    public:
        string frequencySort(string s) {
            vector<unsigned int> count(128, 0);
            for (char c : s)
                count[c]++;
            
            priority_queue<pair<unsigned int, char>> pq;
            for (unsigned int i = 0; i < count.size(); i++) {
                if (count[i] != 0)
                    pq.push({count[i], (char)i});
            }
            
            string result;
            while (! pq.empty()) {
                result.append(pq.top().first, pq.top().second);
                pq.pop();
            }
            
            return result;
        }
    };

Log in to reply
 

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