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

题目

给定一个字符串,请将字符串里的字符按照出现的频率降序排列。

示例 1:

输入:
"tree"

输出:
"eert"

解释:
'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。

分析

哈希表统计词频,优先队列来排序。

代码

class Solution {
    public String frequencySort(String s) {
        PriorityQueue>  pq = new PriorityQueue>(new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                return o2.getValue()-o1.getValue();
            }
        });

        HashMap map = new HashMap();

        for( char c : s.toCharArray()) {

            if (map.containsKey(c)) {
                map.put(c,map.get(c)+1);
            }else {
                map.put(c, 1);
            }
        }

        for (Map.Entry entry : map.entrySet()) {
            pq.add(entry);
        }

        StringBuilder string = new StringBuilder();

        while(pq.size() != 0) {
            Map.Entry temp = pq.poll();
            int count = temp.getValue();
            char c = temp.getKey();
            while (count-- >0){
                string.append(c);
            }
        }

        return string.toString();
    }
}

 

你可能感兴趣的:(LeetCode451. 根据字符出现频率排序)