-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek6 451. Sort Characters By Frequency
36 lines (36 loc) · 1.16 KB
/
week6 451. Sort Characters By Frequency
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
public class Solution {
public String frequencySort(String s){
char[] array = s.toCharArray();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max = 1;
for (int i = 0; i < array.length; i++) {
Integer temp = map.get(array[i]);
if (temp == null) {
map.put(array[i], 1);
} else {
map.put(array[i], temp + 1);
max = Math.max(max, temp + 1);
}
}
List<Character>[] list = new List[max + 1];
for (Character c : map.keySet()) {
int num = map.get(c);
if (list[num] == null) {
list[num] = new ArrayList();
}
list[num].add(c);
}
StringBuilder sb = new StringBuilder();
for (int i = list.length - 1; i >= 0; i--) {
List<Character> subList = list[i];
if (subList != null) {
for (Character c : subList) {
for (int j = 0; j < i; j++) {
sb.append(c);
}
}
}
}
return sb.toString();
}
}