Back
Featured image of post String Freq Sort

String Freq Sort

How many times have you disappeared?

Leetcode 451

451. 根据字符出现频率排序

利用hashmap记录 , 或者用数组模拟hashmap , 然后利用PriorityQueue大顶堆来排序

public String frequencySort(String s) {
        StringBuilder sb = new StringBuilder();
        //Map<Character , Integer> map = new HashMap<>();
        //for (char ch : s.toCharArray()){
        //   map.put(ch , map.getOrDefault(ch , 0 ) + 1);
        //}
        //也可以开一个128的数组替换 , 优化性能
        int[] frequency = new int[128];
        for (char ch : s.toCharArray()){
            frequency[ch]++;
        }

        PriorityQueue<node> pq = new PriorityQueue<node>((o1 , o2) -> o1.freq != o2.freq ? o2.freq - o1.freq : o1.ch - o2.ch);
        //for (char ch : map.keySet()){
        //    pq.offer(new node(ch , map.get(ch)));
        //}

        for (int i = 0; i < frequency.length; i++) {
            if (frequency[i] != 0){
                pq.add(new node((char) (i) , frequency[i]));
            }
        }

        while (!pq.isEmpty()){
            node poll = pq.poll();
            int cnt = poll.freq;
            while (cnt-- > 0){
                sb.append(poll.ch);
            }
        }

        return sb.toString();
    }


class node {//存储字符和频率
    char ch;
    int freq;

    node(char ch , int freq){
        this.ch = ch;
        this.freq = freq;
    }
}
Welcome to the world of Minezeratul