> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/heap/xuan-chu-chu-xian-pin-lv-zui-gao-de-k-ge/sort-characters-by-frequency.md).

# Sort Characters By Frequency

<https://leetcode.com/problems/sort-characters-by-frequency/description/>

> 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.
>
> Example 2:
>
> Input:
>
> "cccaaa"
>
> Output:
>
> "cccaaa"
>
> Explanation:
>
> Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
>
> Note that "cacaca" is incorrect, as the same characters must be together.
>
> Example 3:
>
> Input:
>
> "Aabb"
>
> Output:
>
> "bbAa"
>
> Explanation:
>
> "bbaA" is also a valid answer, but "Aabb" is incorrect.
>
> Note that 'A' and 'a' are treated as two different characters.

## Thoughts

想法很直观，把每个字符出现的频率统计下来存在map里然后再把map的entry一一存到max pq里。

## Code

```
class Solution {
    public String frequencySort(String s) {
        PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(
            new Comparator<Map.Entry<Character, Integer>>() {
                @Override
                public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b) {
                    return b.getValue() - a.getValue();
                }
            }
        );
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (!map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), 1);
            } else {
                map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
            }
        }
        pq.addAll(map.entrySet());
        StringBuilder sb = new StringBuilder();
        while (!pq.isEmpty()) {
            Map.Entry e = pq.poll();
            for (int i = 0; i < (int)e.getValue(); i++) {
                sb.append(e.getKey());
            }
        }
        return sb.toString();
    }
}
```

## Analysis

时间复杂度O(nlgn)
