-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1405_longest_happy_string.java
65 lines (53 loc) · 1.59 KB
/
1405_longest_happy_string.java
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.PriorityQueue;
class Solution {
public String longestDiverseString(int a, int b, int c) {
PriorityQueue<Pair> pq = new PriorityQueue<>();
if (a > 0) {
pq.add(new Pair('a', a));
}
if (b > 0) {
pq.add(new Pair('b', b));
}
if (c > 0) {
pq.add(new Pair('c', c));
}
StringBuilder res = new StringBuilder();
while (!pq.isEmpty()) {
char currChar = pq.peek().ch;
int currCount = pq.peek().count;
pq.poll();
int resLen = res.length();
if (resLen > 1 && res.charAt(resLen - 1) == currChar && res.charAt(resLen - 2) == currChar) {
if (pq.isEmpty()) {
break;
}
char nextChar = pq.peek().ch;
int nextCount = pq.peek().count;
pq.poll();
res.append(nextChar);
nextCount--;
if (nextCount > 0) {
pq.offer(new Pair(nextChar, nextCount));
}
} else {
res.append(currChar);
currCount--;
}
if (currCount > 0) {
pq.offer(new Pair(currChar, currCount));
}
}
return res.toString();
}
}
class Pair implements Comparable<Pair> {
char ch;
int count;
Pair(char ch, int count) {
this.ch = ch;
this.count = count;
}
public int compareTo(Pair that) {
return that.count - this.count;
}
}