Skip to content

Commit e2dae45

Browse files
authored
Update Sort Characters By Frequency.java
1 parent a5b5c5a commit e2dae45

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed
Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,41 @@
11
class Solution {
22
public String frequencySort(String s) {
3-
Map<Character, Integer> map = new HashMap<>();
3+
int[] freqMap = new int[62];
4+
int maxFrequency = 0;
45
for (char c : s.toCharArray()) {
5-
map.put(c, map.getOrDefault(c, 0) + 1);
6+
int charIdx = getCharIndex(c);
7+
freqMap[charIdx]++;
8+
maxFrequency = Math.max(maxFrequency, freqMap[charIdx]);
9+
}
10+
List<Character>[] revMap = new List[maxFrequency + 1];
11+
for (int i = 0; i < 62; i++) {
12+
char c = getDecodedChar(i);
13+
int currFreq = freqMap[i];
14+
if (currFreq != 0) {
15+
if (revMap[currFreq] == null) {
16+
revMap[currFreq] = new ArrayList<>();
17+
}
18+
revMap[currFreq].add(c);
19+
}
620
}
7-
PriorityQueue<Character> pq = new PriorityQueue<>((o1, o2) -> map.get(o2) - map.get(o1));
8-
pq.addAll(map.keySet());
921
StringBuilder sb = new StringBuilder();
10-
while (!pq.isEmpty()) {
11-
char c = pq.poll();
12-
int count = map.get(c);
13-
while (count-- > 0) {
14-
sb.append(c);
22+
for (int i = maxFrequency; i > 0; i--) {
23+
if (revMap[i] != null) {
24+
List<Character> characterList = revMap[i];
25+
for (char c : characterList) {
26+
sb.append(String.valueOf(c).repeat(i));
27+
}
1528
}
1629
}
1730
return sb.toString();
1831
}
19-
}
2032

33+
private char getDecodedChar(int idx) {
34+
return (char) (idx < 26 ? 97 + idx : (idx >= 52 ? 48 + idx - 52 : 65 + idx - 26));
35+
}
36+
37+
private int getCharIndex(char c) {
38+
return Character.isDigit(c) ? 52 + c - '0'
39+
: (Character.isUpperCase(c) ? c - 'A' + 26 : c - 'a');
40+
}
41+
}

0 commit comments

Comments
 (0)