Skip to content

Commit

Permalink
add day 22
Browse files Browse the repository at this point in the history
  • Loading branch information
ravaan committed May 22, 2020
1 parent 213de89 commit 621acfe
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions 22-SortCharactersByFrequency.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,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();
}
}
}

0 comments on commit 621acfe

Please sign in to comment.