LeetCode 451. Sort Characters By Frequency 根據字符出現頻率排序 (C++/Java)

題目:

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

Example 1:ui

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

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

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.

分析:

給定一個字符串,請將字符串裏的字符按照出現的頻率降序排列。blog

基本思路就是遍歷一遍字符串,將字符出現的次數存進Hashmap中,再遍歷一遍Hashmap將字符和出現次數做爲一組pair存進優先級隊列中,再從隊列中依次取出數據拼接成最後的字符串。three

程序:

C++隊列

class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> m;
        for(const auto& c:s)
            m[c]++;
        priority_queue <pair<char, int>, vector<pair<char, int>>, cmp >q;
        for(const auto& i:m){
            q.push(make_pair(i.first, i.second));
        }
        string res = "";
        while(!q.empty()){
            res.append(q.top().second, q.top().first);
            q.pop();
        }
        return res;
    }
private:
    struct cmp{
        bool operator() (pair<char, int> a, pair<char, int> b)
        {
            return a.second < b.second;
        }
    };
};

Java字符串

class Solution {
    public String frequencySort(String s) {
        for(char c:s.toCharArray()){
            map.put(c, map.getOrDefault(c,0) + 1);
        }
        p.addAll(map.entrySet());
        while(!p.isEmpty()){
            Map.Entry<Character, Integer> e = p.poll();
            for(int i = 0; i < e.getValue().intValue(); i++){
                res.append(e.getKey());
            }
        }
        return res.toString();
    }
    private StringBuilder res = new StringBuilder();
    private HashMap<Character, Integer> map = new HashMap<>();
    private PriorityQueue<Map.Entry<Character, Integer>> p = new PriorityQueue<>(new Comparator<Map.Entry<Character, Integer>>()
    {
        public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b)
        {
            return b.getValue() - a.getValue();
        }
    });
}
相關文章
相關標籤/搜索