Friday, November 4, 2016

Sort Characters By Frequency -- LeetCode

[Question]
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
[Analysis]
First, use a hash table to count the frequency of each letter. Second, use a heap to sort each element in the hash table, based on the frequency. The time complexity is O(N). The space complexity can be constant, as there are fixed number of characters -- the size of heap is O(1).

[Solution]
class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> counter;
        auto comp = [](pair<char, int>& a, pair<char, int>& b) { return a.second <b.second; };
        priority_queue< pair<char,int>, vector<pair<char,int>>, decltype(comp) > sorter(comp);
       
        for(auto& c:s)
            counter[c]++;
           
        for(auto& p:counter)
            sorter.push(p);
       
        string res="";
        while (!sorter.empty()) {
            auto elem = sorter.top();
            sorter.pop();
            for (int i=0; i<elem.second; i++)
                res+=elem.first;
        }
       
        return res;
    }

};

No comments:

Post a Comment