Skip to content

Commit 19583d3

Browse files
authored
Create 1405-longest-happy-string.js
1 parent db64a15 commit 19583d3

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* PriorityQueue
3+
* Time O(n*log(n)) | Space O(n)
4+
* https://leetcode.com/problems/longest-happy-string/
5+
* @param {number} a
6+
* @param {number} b
7+
* @param {number} c
8+
* @return {string}
9+
*/
10+
var longestDiverseString = function(a, b, c) {
11+
12+
const maxQ = new MaxPriorityQueue({
13+
compare: (a,b) => {
14+
return b[0]-a[0];
15+
}
16+
});
17+
18+
a && maxQ.enqueue([a, "a"]);
19+
b && maxQ.enqueue([b, "b"]);
20+
c && maxQ.enqueue([c, "c"]);
21+
22+
let happyStr = "";
23+
24+
while(!maxQ.isEmpty()) {
25+
26+
let [count, char] = maxQ.dequeue();
27+
28+
if(happyStr[happyStr.length - 1] === char &&
29+
happyStr[happyStr.length - 2] === char) {
30+
31+
if(!maxQ.isEmpty()) {
32+
let [count1, char1] = maxQ.dequeue();
33+
34+
happyStr += char1;
35+
count1--;
36+
37+
count1 && maxQ.enqueue([count1, char1]);
38+
maxQ.enqueue([count, char]);
39+
}
40+
} else {
41+
42+
if(count >= 2) {
43+
happyStr += char.repeat(2);
44+
count -= 2;
45+
} else {
46+
happyStr += char;
47+
count--;
48+
}
49+
50+
count && maxQ.enqueue([count, char]);
51+
}
52+
}
53+
54+
return happyStr;
55+
};

0 commit comments

Comments
 (0)