451. Sort Characters By Frequency

题目链接:https://leetcode.com/problems...

hashmap求frequency加排序,排序可以用bucket sort or heap sort。

bucket sort:

public class Solution {
    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap();
        int max = 0;
        for(char c : s.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
            max = Math.max(map.get(c), max);
        }
        
        List<Character>[] bucket = new List[max + 1];
        int count = 0;
        for(char c : map.keySet()) {
            int index = map.get(c);
            if(bucket[index] == null) bucket[index] = new ArrayList();
            bucket[index].add(c);
            count++;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("");
        for(int i = bucket.length-1; i >= 0; i--) {
            if(bucket[i] != null) {
                for(char c : bucket[i]) {
                    for(int j = 0; j < i; j++)  sb.append(c);
                    count--;
                }
                if(count == 0) break;
            }
        }
        return sb.toString();
    }
}

heap sort参考discussion:
https://discuss.leetcode.com/...


lulouch13
13 声望6 粉丝