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
相关文章
相关标签/搜索