[leetcode] 451. Sort Characters By Frequency

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.

這道題是按字符出現頻率排序字符串,題目難度爲Medium。

首先統計每個字符出現的次數,後續處理思路有很多種,這裏藉助桶排序的方法來方便最終字符串的構築。具體代碼:

class Solution {
public:
    string frequencySort(string s) {
        vector<int> freq(256, 0);
        vector<string> bucket(s.size()+1, "");
        string ret = "";
        
        for(auto ch:s) ++freq[ch];
        for(int i=0; i<256; ++i)
            bucket[freq[i]] += string(freq[i], i);
        for(int i=bucket.size()-1; i>0; --i)
            ret += bucket[i];
            
        return ret;
    }
};

統計完每個字符出現的次數後,將次數相同的字符放在同一個桶中,最終從大到小遍歷所有桶即可得出排序後的字符串,時間複雜度爲O(n)。

這道題和第347題非常相似,大家可以順便看下第347題(傳送門)。同理這裏也可以用堆來進行處理,依據字符出現次數入堆,然後依次從堆中取出各字符即可得出最終結果。由於需要建堆,時間複雜度爲O(nlogn)。具體代碼:

class Solution {
public:
    string frequencySort(string s) {
        vector<int> freq(256, 0);
        priority_queue<pair<int, char>> heap;
        string ret = "";
        
        for(auto ch:s) ++freq[ch];
        for(int i=0; i<256; ++i)
            if(freq[i]) heap.push(make_pair(freq[i], i));
        while(!heap.empty()) {
            pair<int, char> p = heap.top();
            ret += string(p.first, p.second);
            heap.pop();
        }
        
        return ret;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章