Skip to content

Commit edcdfa7

Browse files
Create 0451-sort-characters-by-frequency.java
1 parent 24aaa96 commit edcdfa7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public String frequencySort(String s) {
3+
Map<Character, Integer> map = new HashMap<>();
4+
for(char c: s.toCharArray())
5+
map.put(c, map.getOrDefault(c, 0) + 1);
6+
7+
PriorityQueue<pair> q = new PriorityQueue<>((a, b) -> b.f - a.f);
8+
for(char c: map.keySet())
9+
q.add(new pair(c, map.get(c)));
10+
11+
StringBuilder res = new StringBuilder();
12+
while(!q.isEmpty()){
13+
pair r = q.poll();
14+
int f = r.f;
15+
while(f > 0){
16+
res.append(r.c);
17+
f--;
18+
}
19+
}
20+
return res.toString();
21+
}
22+
}
23+
class pair{
24+
char c;
25+
int f;
26+
27+
public pair(char c, int f){
28+
this.c = c;
29+
this.f = f;
30+
}
31+
}

0 commit comments

Comments
 (0)