|
1 | 1 | class Solution {
|
2 | 2 | public String frequencySort(String s) {
|
3 |
| - Map<Character, Integer> map = new HashMap<>(); |
| 3 | + int[] freqMap = new int[62]; |
| 4 | + int maxFrequency = 0; |
4 | 5 | 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 | + } |
6 | 20 | }
|
7 |
| - PriorityQueue<Character> pq = new PriorityQueue<>((o1, o2) -> map.get(o2) - map.get(o1)); |
8 |
| - pq.addAll(map.keySet()); |
9 | 21 | 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 | + } |
15 | 28 | }
|
16 | 29 | }
|
17 | 30 | return sb.toString();
|
18 | 31 | }
|
19 |
| -} |
20 | 32 |
|
| 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