-
Notifications
You must be signed in to change notification settings - Fork 29
/
Solution451.java
42 lines (34 loc) · 1.2 KB
/
Solution451.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package hash_table_problem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Solution451 {
public String frequencySort(String s) {
// 1、创建 HashMap 字符:频率
HashMap<Character, Integer> freqCharMap = new HashMap<>();
for (Character c:s.toCharArray()) {
freqCharMap.put(c, freqCharMap.getOrDefault(c, 0) + 1);
}
// 2、创建桶 ArrayList[] 频率:字符列表
List<Character>[] freqCharList = new ArrayList[s.length() + 1];
for (char c:freqCharMap.keySet()) {
int f = freqCharMap.get(c);
if (freqCharList[f] == null) {
freqCharList[f] = new ArrayList<>();
}
freqCharList[f].add(c);
}
// 3、拼装按频率高-低的字符串
StringBuilder sb = new StringBuilder();
for (int i = freqCharList.length - 1; i >= 0; i--) {
if (freqCharList[i] != null) {
for (char c:freqCharList[i]) {
for (int j = 0; j < i; j++) {
sb.append(c);
}
}
}
}
return sb.toString();
}
}