-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution451.java
53 lines (41 loc) · 1.18 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
43
44
45
46
47
48
49
50
51
52
53
package leetcode.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Solution451 {
static class CharNum implements Comparable<CharNum> {
char c;
int num;
public CharNum(char c) {
this.c = c;
this.num = 1;
}
@Override
public int compareTo(CharNum o) {
return o.num - this.num;
}
}
public String frequencySort(String s) {
char[] charArray = s.toCharArray();
HashMap<Character, CharNum> map = new HashMap<>();
ArrayList<CharNum> list = new ArrayList<>();
for (char c : charArray) {
if (map.containsKey(c)) {
map.get(c).num++;
} else {
CharNum charNum = new CharNum(c);
list.add(charNum);
map.put(c, charNum);
}
}
Collections.sort(list);
StringBuilder res = new StringBuilder();
for (CharNum charNum : list) {
while (charNum.num != 0) {
charNum.num--;
res.append(charNum.c);
}
}
return res.toString();
}
}