[LC] 451. 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.

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);
    }
}

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/12315495.html