-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1405_Longest_Happy_String.java
More file actions
62 lines (53 loc) 路 16 KB
/
Copy path1405_Longest_Happy_String.java
File metadata and controls
62 lines (53 loc) 路 16 KB
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
class Solution {
public String longestDiverseString(int a, int b, int c) {
PriorityQueue<Pair> pq = new PriorityQueue<Pair>((x, y) ->
(y.count - x.count)
);
// Add the counts of a, b and c in priority queue.
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 ans = new StringBuilder();
while (!pq.isEmpty()) {
Pair p = pq.poll();
int count = p.count;
char character = p.character;
// If three consecutive characters exists, pick the second most
// frequent character.
if (
ans.length() >= 2 &&
ans.charAt(ans.length() - 1) == p.character &&
ans.charAt(ans.length() - 2) == p.character
) {
if (pq.isEmpty()) break;
Pair temp = pq.poll();
ans.append(temp.character);
if (temp.count - 1 > 0) {
pq.add(new Pair(temp.count - 1, temp.character));
}
} else {
count--;
ans.append(character);
}
// If count is greater than zero, add it to priority queue.
if (count > 0) {
pq.add(new Pair(count, character));
}
}
return ans.toString();
}
class Pair {
int count;
char character;
Pair(int count, char character) {
this.count = count;
this.character = character;
}
}
}