-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1405-longest-happy-string.js
55 lines (43 loc) · 1.25 KB
/
1405-longest-happy-string.js
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
/**
* PriorityQueue
* Time O(n*log(n)) | Space O(n)
* https://leetcode.com/problems/longest-happy-string/
* @param {number} a
* @param {number} b
* @param {number} c
* @return {string}
*/
var longestDiverseString = function(a, b, c) {
const maxQ = new MaxPriorityQueue({
compare: (a,b) => {
return b[0]-a[0];
}
});
a && maxQ.enqueue([a, "a"]);
b && maxQ.enqueue([b, "b"]);
c && maxQ.enqueue([c, "c"]);
let happyStr = "";
while(!maxQ.isEmpty()) {
let [count, char] = maxQ.dequeue();
if(happyStr[happyStr.length - 1] === char &&
happyStr[happyStr.length - 2] === char) {
if(!maxQ.isEmpty()) {
let [count1, char1] = maxQ.dequeue();
happyStr += char1;
count1--;
count1 && maxQ.enqueue([count1, char1]);
maxQ.enqueue([count, char]);
}
} else {
if(count >= 2) {
happyStr += char.repeat(2);
count -= 2;
} else {
happyStr += char;
count--;
}
count && maxQ.enqueue([count, char]);
}
}
return happyStr;
};