leetcode solution: Sort Characters By Frequency (451)

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
5
6
7
8
9
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.

解法1:

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Solution {
public String frequencySort(String s) {
Map<Character, Integer> map = new HashMap<Character,Integer>();
for (char c: s.toCharArray()) {
map.put(c, map.getOrDefault(c,0) + 1);
}
List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
Comparator<Map.Entry<Character,Integer>> comparator = new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Map.Entry<Character, Integer> left, Map.Entry<Character, Integer> right) {
return right.getValue().compareTo(left.getValue());
}
};
list.sort(comparator);
// Create String
StringBuffer ss = new StringBuffer();
for (Map.Entry<Character, Integer> entry : list) {
for (int i = 0; i < entry.getValue(); ++i) {
ss.append(entry.getKey());
}
}
return ss.toString();
}
}