-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1405. Longest Happy String
More file actions
29 lines (26 loc) · 992 Bytes
/
1405. Longest Happy String
File metadata and controls
29 lines (26 loc) · 992 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public String longestDiverseString(int a, int b, int c) {
StringBuilder sb = new StringBuilder();
PriorityQueue<int[]> pq = new PriorityQueue<>((x, y) -> y[1] - x[1]);
if (a > 0) pq.add(new int[]{'a', a});
if (b > 0) pq.add(new int[]{'b', b});
if (c > 0) pq.add(new int[]{'c', c});
while (!pq.isEmpty()) {
int first[] = pq.poll();
int len = sb.length();
if (len >= 2 && sb.charAt(len - 1) == first[0] && sb.charAt(len - 2) == first[0]) {
if (pq.isEmpty()) continue;
int second[] = pq.poll();
sb.append((char) second[0]);
second[1]--;
if (second[1] > 0) pq.add(second);
pq.add(first);
} else {
sb.append((char) first[0]);
first[1]--;
if (first[1] > 0) pq.add(first);
}
}
return sb.toString();
}
}