-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHEAP_451
More file actions
23 lines (23 loc) · 687 Bytes
/
Copy pathHEAP_451
File metadata and controls
23 lines (23 loc) · 687 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public String frequencySort(String s) {
HashMap<Character, Integer> map = new HashMap<>();
for(char ch : s.toCharArray()){
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
PriorityQueue<Character> pq = new PriorityQueue<>(
(a, b) -> map.get(b) - map.get(a)
);
for(char ch : map.keySet()){
pq.offer(ch);
}
StringBuilder ans = new StringBuilder();
while(!pq.isEmpty()){
char ch = pq.poll();
int freq = map.get(ch);
while(freq-- > 0){
ans.append(ch);
}
}
return ans.toString();
}
}