Skip to content

Commit 92b47b5

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 767_Reorganize_String.java
1 parent 308c629 commit 92b47b5

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed
Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,45 @@
11
class Solution {
22
public String reorganizeString(String S) {
33
if (S == null || S.length() == 0) {
4-
return "";
4+
return new String();
55
}
66

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);
99

1010
for (char c : S.toCharArray()) {
1111
hm.put(c, hm.getOrDefault(c, 0) + 1);
1212

13-
if (hm.get(c) > (S.length() + 1) / 2) {
14-
return "";
13+
if (hm.get(c) > hm.get(maxChar)) {
14+
maxChar = c;
1515
}
1616
}
1717

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 "";
2020
}
2121

22-
StringBuilder sb = new StringBuilder();
23-
int[] prev = new int[] { -1, 0 };
22+
int idx = 0;
23+
char[] result = new char[S.length()];
2424

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+
}
2730

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+
}
3136

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+
}
3441
}
3542

36-
return sb.toString();
43+
return String.valueOf(result);
3744
}
3845
}

0 commit comments

Comments
 (0)