451. Sort Characters By Frequency

451. Sort Characters By Frequencyarrow-up-right

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:

My Solutions:

用hash 存贮每个char的频率,然后按照从大到小依次把char加入最终结果。有三种写法:

1。 吊桶:循环所有出现的char

2。 PriorityQueue

3。吊桶:只循环128个unicode (最快)

方法1:

方法2:

方法3:

Last updated