# 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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/heap/xuan-chu-chu-xian-pin-lv-zui-gao-de-k-ge/sort-characters-by-frequency.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
