[LeetCode] Sort Characters By Frequency 根據字符出現頻率排序

 

Given a string, sort it in decreasing order based on the frequency of characters.html

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:app

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:post

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.

 

這道題讓咱們給一個字符串按照字符出現的頻率來排序,那麼毫無疑問確定要先統計出每一個字符出現的個數,那麼以後怎麼作呢?咱們能夠利用優先隊列的自動排序的特色,把個數和字符組成pair放到優先隊列裏排好序後,再取出來組成結果res便可,參見代碼以下:url

 

解法一:spa

class Solution {
public:
    string frequencySort(string s) {
        string res = "";
        priority_queue<pair<int, char>> q;
        unordered_map<char, int> m;
        for (char c : s) ++m[c];
        for (auto a : m) q.push({a.second, a.first});
        while (!q.empty()) {
            auto t = q.top(); q.pop();
            res.append(t.first, t.second);
        }
        return res;
    }
};

 

咱們也可使用STL自帶的sort來作,關鍵就在於重寫comparator,因爲須要使用外部變量,記得中括號中放入&,而後咱們將頻率大的返回,注意必定還要處理頻率相等的狀況,要否則兩個頻率相等的字符可能穿插着出如今結果res中,這樣是不對的。參見代碼以下:code

 

解法二:htm

class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> m;
        for (char c : s) ++m[c];
        sort(s.begin(), s.end(), [&](char& a, char& b){
            return m[a] > m[b] || (m[a] == m[b] && a < b);
        });
        return s;
    }
};

 

咱們也能夠不使用優先隊列,而是創建一個字符串數組,由於某個字符的出現次數不可能超過s的長度,因此咱們將每一個字符根據其出現次數放入數組中的對應位置,那麼最後咱們只要從後往前遍歷數組全部位置,將不爲空的位置的字符串加入結果res中便可,參見代碼以下:blog

 

解法三:排序

class Solution {
public:
    string frequencySort(string s) {
        string res;
        vector<string> v(s.size() + 1);
        unordered_map<char, int> m;
        for (char c : s) ++m[c];
        for (auto &a : m) {
            v[a.second].append(a.second, a.first);
        }
        for (int i = s.size(); i > 0; --i) {
            if (!v[i].empty()) res.append(v[i]);
        }
        return res;
    }
};

 

相似題目:

Top K Frequent Words

First Unique Character in a String

 

參考資料:

https://leetcode.com/problems/sort-characters-by-frequency/description/

https://leetcode.com/problems/sort-characters-by-frequency/discuss/93404/c-on-solution-without-sort

https://leetcode.com/problems/sort-characters-by-frequency/discuss/93409/concise-c-solution-using-stl-sort

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索