|
1 | 1 | class Solution {
|
2 |
| - public String reorganizeString(String S) { |
3 |
| - if (S == null || S.length() == 0) { |
4 |
| - return new String(); |
| 2 | + private class LetterCount { |
| 3 | + private char letter; |
| 4 | + private int count; |
| 5 | + |
| 6 | + public LetterCount(char letter, int count) { |
| 7 | + this.letter = letter; |
| 8 | + this.count = count; |
5 | 9 | }
|
| 10 | + } |
6 | 11 |
|
| 12 | + public String reorganizeString(String s) { |
7 | 13 | Map<Character, Integer> hm = new HashMap<>();
|
8 |
| - char maxChar = S.charAt(0); |
9 | 14 |
|
10 |
| - for (char c : S.toCharArray()) { |
| 15 | + for (char c : s.toCharArray()) { |
11 | 16 | hm.put(c, hm.getOrDefault(c, 0) + 1);
|
12 |
| - |
13 |
| - if (hm.get(c) > hm.get(maxChar)) { |
14 |
| - maxChar = c; |
15 |
| - } |
16 | 17 | }
|
17 | 18 |
|
18 |
| - if (hm.get(maxChar) > (S.length() + 1) / 2) { |
19 |
| - return ""; |
| 19 | + PriorityQueue<LetterCount> pq = new PriorityQueue<>((a, b) -> Integer.compare(b.count, a.count)); |
| 20 | + |
| 21 | + for (Map.Entry<Character, Integer> entry : hm.entrySet()) { |
| 22 | + pq.offer(new LetterCount(entry.getKey(), entry.getValue())); |
20 | 23 | }
|
21 | 24 |
|
22 | 25 | int idx = 0;
|
23 |
| - char[] result = new char[S.length()]; |
| 26 | + char[] result = new char[s.length()]; |
24 | 27 |
|
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 |
| - } |
| 28 | + while (!pq.isEmpty()) { |
| 29 | + if (idx == 0 || pq.peek().letter != result[idx - 1]) { |
| 30 | + LetterCount l = pq.poll(); |
| 31 | + result[idx] = l.letter; |
| 32 | + l.count--; |
30 | 33 |
|
31 |
| - for (char c : hm.keySet()) { |
32 |
| - while (hm.get(c) > 0) { |
33 |
| - if (idx >= S.length()) { |
34 |
| - idx = 1; |
| 34 | + if (l.count > 0) { |
| 35 | + pq.offer(l); |
35 | 36 | }
|
| 37 | + } else { |
| 38 | + LetterCount firstResult = pq.poll(); |
36 | 39 |
|
37 |
| - result[idx] = c; |
38 |
| - idx += 2; |
39 |
| - hm.put(c, hm.get(c) - 1); |
| 40 | + if (pq.isEmpty()) { |
| 41 | + return ""; |
| 42 | + } |
| 43 | + |
| 44 | + LetterCount secondResult = pq.poll(); |
| 45 | + result[idx] = secondResult.letter; |
| 46 | + secondResult.count--; |
| 47 | + |
| 48 | + if (secondResult.count > 0) { |
| 49 | + pq.offer(secondResult); |
| 50 | + } |
| 51 | + |
| 52 | + if (firstResult.count > 0) { |
| 53 | + pq.offer(firstResult); |
| 54 | + }
562D
code> |
40 | 55 | }
|
| 56 | + |
| 57 | + ++idx; |
41 | 58 | }
|
42 | 59 |
|
43 | 60 | return String.valueOf(result);
|
|
0 commit comments