-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22-SortCharactersByFrequency.java
More file actions
33 lines (30 loc) · 1.02 KB
/
22-SortCharactersByFrequency.java
File metadata and controls
33 lines (30 loc) · 1.02 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
class Solution {
public String frequencySort(String s) {
int len = s.length();
if (len == 0) return "";
int[] map = new int[128];
for (char c : s.toCharArray()) {
map[c - '\u0000']++;
}
// System.out.println(Arrays.toString(map));
PriorityQueue<Pair<Character, Integer>> pq = new PriorityQueue<>(new SortByFreq());
for (int i = 0; i < 128; i++) {
if (map[i] != 0) {
pq.add(new Pair((char) i, map[i]));
}
}
StringBuilder ans = new StringBuilder();
while (!pq.isEmpty()) {
Pair<Character, Integer> p = pq.poll();
for (int i = 0; i < p.getValue(); i++) {
ans.append(p.getKey());
}
}
return ans.toString();
}
class SortByFreq implements Comparator<Pair<Character, Integer>> {
public int compare(Pair<Character, Integer> p1, Pair<Character, Integer> p2) {
return p2.getValue() - p1.getValue();
}
}
}