-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLeetCode451.java
More file actions
58 lines (52 loc) · 1.78 KB
/
Copy pathLeetCode451.java
File metadata and controls
58 lines (52 loc) · 1.78 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package LeetCode;
import java.util.*;
public class LeetCode451 {
public String frequencySort(String s) {
HashMap<Character, Integer> map = new HashMap<>();
StringBuilder builder = new StringBuilder();
for (char c : s.toCharArray()) {
map.merge(c, 1, (a, b) -> a+b);
}
List[] bucket = new List[s.length()+1];
for (char c : map.keySet()) {
if (bucket[map.get(c)] == null) bucket[map.get(c)] = new ArrayList();
bucket[map.get(c)].add(c);
}
for (List list : bucket) {
if (list != null) System.out.println(list);
}
for (int i = bucket.length-1; i > 0; i--) {
if (bucket[i] != null) {
for (Object o : bucket[i]) {
char c = (char) o;
System.out.println("c: " + c);
for (int j = 0; j < i; j++) {
builder.append(c);
}
}
}
}
return builder.toString();
}
public String frequencySort2(String s) {
char[] sArr = s.toCharArray();
int[] count = new int[128];
for (char c : sArr) count[c]++;
int pos = 0;
while (pos < sArr.length) {
int max = 0;
for (int i = 1; i < 128; i++) {
if (count[i] > count[max]) max = i;
}
for (int i = 0; i < count[max]; i++) {
sArr[pos++] = (char) max;
}
count[max] = 0;
}
return new String(sArr);
}
public static void main(String[] args) {
LeetCode451 instance = new LeetCode451();
System.out.println(instance.frequencySort2("tree"));
}
}