|
1 | 1 | class Solution {
|
2 | 2 | public String reorganizeString(String S) {
|
3 | 3 | if (S == null || S.length() == 0) {
|
4 |
| - return ""; |
| 4 | + return new String(); |
5 | 5 | }
|
6 | 6 |
|
7 |
| - HashMap<Character, Integer> hm = new HashMap<>(); |
8 |
| - PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]); |
| 7 | + Map<Character, Integer> hm = new HashMap<>(); |
| 8 | + char maxChar = S.charAt(0); |
9 | 9 |
|
10 | 10 | for (char c : S.toCharArray()) {
|
11 | 11 | hm.put(c, hm.getOrDefault(c, 0) + 1);
|
12 | 12 |
|
13 |
| - if (hm.get(c) > (S.length() + 1) / 2) { |
14 |
| - return ""; |
| 13 | + if (hm.get(c) > hm.get(maxChar)) { |
| 14 | + maxChar = c; |
15 | 15 | }
|
16 | 16 | }
|
17 | 17 |
|
18 |
| - for (char key : hm.keySet()) { |
19 |
| - pq.offer(new int[] { key, hm.get(key) }); |
| 18 | + if (hm.get(maxChar) > (S.length() + 1) / 2) { |
| 19 | + return ""; |
20 | 20 | }
|
21 | 21 |
|
22 |
| - StringBuilder sb = new StringBuilder(); |
23 |
| - int[] prev = new int[] { -1, 0 }; |
| 22 | + int idx = 0; |
| 23 | + char[] result = new char[S.length()]; |
24 | 24 |
|
25 |
| - while (!pq.isEmpty()) { |
26 |
| - int[] curr = pq.poll(); |
| 25 | + while (idx < S.length() && hm.get(maxChar) > 0) { |
| 26 | + result[idx] = maxChar; |
| 27 | + idx += 2; |
| 28 | + hm.put(maxChar, hm.get(maxChar) - 1); |
| 29 | + } |
27 | 30 |
|
28 |
| - if (--prev[1] > 0) { |
29 |
| - pq.offer(prev); |
30 |
| - } |
| 31 | + for (char c : hm.keySet()) { |
| 32 | + while (hm.get(c) > 0) { |
| 33 | + if (idx >= S.length()) { |
| 34 | + idx = 1; |
| 35 | + } |
31 | 36 |
|
32 |
| - sb.append((char) curr[0]); |
33 |
| - prev = curr; |
| 37 | + result[idx] = c; |
| 38 | + idx += 2; |
| 39 | + hm.put(c, hm.get(c) - 1); |
| 40 | + } |
34 | 41 | }
|
35 | 42 |
|
36 |
| - return sb.toString(); |
| 43 | + return String.valueOf(result); |
37 | 44 | }
|
38 | 45 | }
|
0 commit comments