451. Sort Characters By Frequency將單詞中的字母按照從高頻到低頻的順序輸出

[抄題]:算法

Given a string, sort it in decreasing order based on the frequency of characters.數據結構

Example 1:app

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.

 [暴力解法]:ide

時間分析:優化

空間分析:ui

 [優化後]:spa

時間分析:debug

空間分析:code

[奇葩輸出條件]:對象

[奇葩corner case]:

[思惟問題]:

不知道怎麼存進pq

[英文數據結構或算法,爲何不用別的數據結構或算法]:

只放一個hashmap元素:要用map.entrySet() 用得很少

Map.Entry表明一個哈希表實體

 

[一句話思路]:

[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):

[畫圖]:

[一刷]:

 

e.getKey()是否是字母,也不是對象。不用命名,直接存就好了Map.Entry中的

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

[總結]:

pq中存Map.Entry 表明一個哈希表實體

 

[複雜度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

pq類中有類,類中有方法

 

PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(
            new Comparator<Map.Entry<Character, Integer>>() {
                @Override
                public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b) {
                    return b.getValue() - a.getValue();
                }
            }
        );

 

[其餘解法]:

[Follow Up]:

[LC給出的題目變變變]:

 [代碼風格] :

 [是否頭一次寫此類driver funcion的代碼] :

 [潛臺詞] :

 

class Solution {
    public String frequencySort(String s) {
        //ini: res map
        String res = new String();
        Map<Character, Integer> map = new HashMap<>();
        
        //cc
        if (s == null || s.length() == 0) return res;
        
        //count char
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            }
            else map.put(c, 1);
        }
        
        //pq
        PriorityQueue<Map.Entry<Character, Integer>> pq = 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();
                }
            } 
        );
        
        //append to answer
        pq.addAll(map.entrySet());
        StringBuilder sb = new StringBuilder();
        while (!pq.isEmpty()) {
            Map.Entry e = pq.poll();
            //char ch = e.getKey();
            for (int i = 0; i < (int)e.getValue(); i++) {
                sb.append(e.getKey());
            }
        }
        
        //return new string
        return sb.toString();
    }
}
View Code
相關文章
相關標籤/搜索