8000 Update `767_Reorganize_String.java` · seanprashad/leetcode-patterns@62a2a82 · GitHub
[go: up one dir, main page]

Skip to content

Commit 62a2a82

Browse files
committed
Update 767_Reorganize_String.java
1 parent e252c67 commit 62a2a82

File tree

1 file changed

+41
-24
lines changed

1 file changed

+41
-24
lines changed

Top K Elements/767_Reorganize_String.java

Lines changed: 41 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,60 @@
11
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;
59
}
10+
}
611

12+
public String reorganizeString(String s) {
713
Map<Character, Integer> hm = new HashMap<>();
8-
char maxChar = S.charAt(0);
914

10-
for (char c : S.toCharArray()) {
15+
for (char c : s.toCharArray()) {
1116
hm.put(c, hm.getOrDefault(c, 0) + 1);
12-
13-
if (hm.get(c) > hm.get(maxChar)) {
14-
maxChar = c;
15-
}
1617
}
1718

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()));
2023
}
2124

2225
int idx = 0;
23-
char[] result = new char[S.length()];
26+
char[] result = new char[s.length()];
2427

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--;
3033

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);
3536
}
37+
} else {
38+
LetterCount firstResult = pq.poll();
3639

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+
}
4055
}
56+
57+
++idx;
4158
}
4259

4360
return String.valueOf(result);

0 commit comments

Comments
 (0)
0