码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 451. Sort Characters By Frequency

时间:2020-02-16 01:05:54      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:sed   tput   get   ash   div   asi   priority   character   ret   

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.

class Solution {
    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (Character c : s.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
        pq.addAll(map.entrySet());
        char[] charArr = new char[s.length()];
        int i = 0;
        while (i < charArr.length) {
            Map.Entry<Character, Integer> entry = pq.poll();
            Character cur = entry.getKey();
            Integer times = entry.getValue();
            int j = 0;
            while (j < times) {
                charArr[i + j] = cur;
                j += 1;
            }
            i += times;
        }
        return new String(charArr);
    }
}

 

[LC] 451. Sort Characters By Frequency

标签:sed   tput   get   ash   div   asi   priority   character   ret   

原文地址:https://www.cnblogs.com/xuanlu/p/12315495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!