Skip to content

Commit 40e30d0

Browse files
authored
Update Longest Happy String.java
1 parent d69d6fa commit 40e30d0

File tree

1 file changed

+37
-37
lines changed

1 file changed

+37
-37
lines changed

Medium/Longest Happy String.java

Lines changed: 37 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,42 @@
11
class Solution {
2-
public String longestDiverseString(int a, int b, int c) {
3-
PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((o1, o2) -> o2[1] - o1[1]);
4-
if (a > 0) {
5-
priorityQueue.add(new int[]{0, a});
6-
}
7-
if (b > 0) {
8-
priorityQueue.add(new int[]{1, b});
9-
}
10-
if (c > 0) {
11-
priorityQueue.add(new int[]{2, c});
12-
}
13-
StringBuilder sb = new StringBuilder("zz");
14-
while (!priorityQueue.isEmpty()) {
15-
int[] temp = {-1, -1};
16-
char peekChar = (char) ('a' + priorityQueue.peek()[0]);
17-
if (peekChar == sb.charAt(sb.length() - 1) &&
18-
peekChar == sb.charAt(sb.length() - 2)) {
19-
temp[0] = priorityQueue.peek()[0];
20-
temp[1] = priorityQueue.peek()[1];
21-
priorityQueue.poll();
22-
if (priorityQueue.isEmpty()) {
23-
break;
2+
public String longestDiverseString(int a, int b, int c) {
3+
PriorityQueue<LetterFrequencyPair> pq =
4+
new PriorityQueue<>((p, q) -> q.frequency() - p.frequency());
5+
if (a > 0) {
6+
pq.add(new LetterFrequencyPair('a', a));
7+
}
8+
if (b > 0) {
9+
pq.add(new LetterFrequencyPair('b', b));
10+
}
11+
if (c > 0) {
12+
pq.add(new LetterFrequencyPair('c', c));
2413
}
25-
}
26-
peekChar = (char) ('a' + priorityQueue.peek()[0]);
27-
if (peekChar != sb.charAt(sb.length() - 1) ||
28-
peekChar != sb.charAt(sb.length() - 2)) {
29-
int[] removed = priorityQueue.poll();
30-
sb.append(peekChar);
31-
removed[1]--;
32-
if (removed[1] > 0) {
33-
priorityQueue.add(removed);
14+
StringBuilder sb = new StringBuilder();
15+
while (!pq.isEmpty()) {
16+
LetterFrequencyPair removed = pq.remove();
17+
int frequency = removed.frequency();
18+
int resultLength = sb.length();
19+
if (resultLength >= 2 &&
20+
sb.charAt(resultLength - 1) == removed.letter() &&
21+
sb.charAt(resultLength - 2) == removed.letter()) {
22+
if (pq.isEmpty()) {
23+
break;
24+
}
25+
LetterFrequencyPair temp = pq.remove();
26+
sb.append(temp.letter());
27+
if (temp.frequency() - 1 > 0) {
28+
pq.add(new LetterFrequencyPair(temp.letter(), temp.frequency() - 1));
29+
}
30+
} else {
31+
sb.append(removed.letter());
32+
frequency--;
33+
}
34+
if (frequency > 0) {
35+
pq.add(new LetterFrequencyPair(removed.letter(), frequency));
36+
}
3437
}
35-
}
36-
if (temp[0] != -1) {
37-
priorityQueue.add(temp);
38-
}
38+
return sb.toString();
3939
}
40-
return sb.substring(2).toString();
41-
}
40+
41+
private record LetterFrequencyPair(char letter, int frequency) {}
4242
}

0 commit comments

Comments
 (0)