> For the complete documentation index, see [llms.txt](https://zhongwen.gitbook.io/leetcode-report/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zhongwen.gitbook.io/leetcode-report/medium/451.-sort-characters-by-frequency.md).

# 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();
    }
}
```
