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.

priorityqueue add 是o(logm) m是加进去的总数,这里m是26个字母 最多,

然后while循环会循环N次 总次数是string的长度,logm 其实很小,所以整体o(n)

priority queue, (a,b) -> b-a 从大到小排, a-b 从小到大排

class Solution {
    public String frequencySort(String s) {
        if(s == null || s.length() == 0)
            return "";
        
        
        Map<Character,Integer> map = new HashMap<>();
            
        PriorityQueue<Map.Entry<Character,Integer>> queue = new PriorityQueue<>((a,b) -> b.getValue()- a.getValue());
        
        for(int i = 0; i < s.length();i++){
            map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);
        }
        
        queue.addAll(map.entrySet());
        
        StringBuilder sb = new StringBuilder();
        
        while(!queue.isEmpty()){
            Map.Entry e = queue.poll();
            
            for(int i = 0; i<(int)e.getValue();i++){
                sb.append(e.getKey());
            }
        }
        
        return sb.toString();
        
    }
}

Last updated