# 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.
```

**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.
```

#### 解题报告

使用桶排序法，第n个桶里有出现频率为n的字符。再从后面往前遍历，不断加入为n的字符，返回这个值。

```java
class Solution {
    public String frequencySort(String s) {
        HashMap<Character, Integer> map = new HashMap();
        for(char ss : s.toCharArray()){
            map.put(ss, map.getOrDefault(ss, 0) + 1);
        }
        
        // create a array which can store list
        List<Character>[] bucket = new ArrayList[s.length() + 1];
        for(char c : map.keySet()){
            int val = map.get(c);
            if(bucket[val] == null){
                bucket[val] = new ArrayList();
            }
            bucket[val].add(c);
        }
        
        StringBuilder sb = new StringBuilder();
        // run through from larger freq to lower freq
        for(int i = bucket.length - 1; i >=0; i--){
            if(bucket[i] == null)
                continue;

            for(char c : bucket[i]){
                for(int j = i; j > 0 ; j--)
                    sb.append(c);
            }
        }
        return sb.toString();
    }
}
```


---

# 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://zhongwen.gitbook.io/leetcode-report/medium/451.-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.
