-
Notifications
You must be signed in to change notification settings - Fork 0
/
451-SortCharactersByFrequency.java
44 lines (38 loc) · 1.38 KB
/
451-SortCharactersByFrequency.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
43
44
// 451. Sort Characters By Frequency
class Solution {
public String frequencySort(String s) {
if(s == null || s.length() == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
HashMap<Character, Integer> countMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
if (countMap.containsKey(a)) {
countMap.put(a, countMap.get(a) + 1);
} else {
countMap.put(a, 1);
}
}
// Put all the frequency in the desired bucket - example "tree" -> ee(2) should be in bucket 2
List<Character>[] arr = new List[s.length() + 1];
for (char a : countMap.keySet()) {
int count = countMap.get(a);
if (arr[count] == null) {
arr[count] = new ArrayList<>();
}
arr[count].add(a);
}
for (int i = arr.length - 1; i >=0; i--) {
if (arr[i] != null) {
for (char a : arr[i]) {
int count = i;
for (int j = 0; j < count; j++) {
sb.append(a);
}
}
}
}
return sb.toString();
}
}