Skip to content

Commit 934330d

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 451_Sort_Characters_By_Frequency.java
1 parent 659f8f0 commit 934330d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public String frequencySort(String s) {
3+
if (s == null || s.length() == 0) {
4+
return s;
5+
}
6+
7+
HashMap<Character, Integer> hm = new HashMap<>();
8+
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
9+
StringBuilder sb = new StringBuilder();
10+
11+
for (char c : s.toCharArray()) {
12+
hm.put(c, hm.getOrDefault(c, 0) + 1);
13+
}
14+
15+
pq.addAll(hm.entrySet());
16+
17+
while (!pq.isEmpty()) {
18+
Map.Entry<Character, Integer> entry = pq.poll();
19+
20+
for (int i = 0; i < entry.getValue(); i++) {
21+
sb.append(entry.getKey());
22+
}
23+
}
24+
25+
return sb.toString();
26+
}
27+
}

0 commit comments

Comments
 (0)