forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstruct String With Repeat Limit.js
47 lines (33 loc) · 1.38 KB
/
Construct String With Repeat Limit.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
var repeatLimitedString = function(s, repeatLimit) {
const map = new Map();
for (const char of s) {
const ascii = char.charCodeAt(0) - 97;
if (!map.has(ascii)) map.set(ascii, 0);
map.set(ascii, map.get(ascii) + 1);
}
const maxHeap = new MaxPriorityQueue({ priority: x => x[0] });
map.forEach((count, ascii) => maxHeap.enqueue([ascii, count]));
let resLargestStr = "";
while (!maxHeap.isEmpty()) {
let [topASCII, topCount] = maxHeap.dequeue().element;
const topChar = String.fromCharCode(topASCII + 97);
if (topCount > repeatLimit) {
if (maxHeap.isEmpty()) {
resLargestStr += topChar.repeat(repeatLimit);
return resLargestStr;
}
let [secondASCII, secondCount] = maxHeap.dequeue().element;
const secondChar = String.fromCharCode(secondASCII + 97);
resLargestStr += topChar.repeat(repeatLimit);
resLargestStr += secondChar;
topCount -= repeatLimit;
secondCount -= 1;
maxHeap.enqueue([topASCII, topCount]);
if (secondCount > 0) maxHeap.enqueue([secondASCII, secondCount]);
}
else {
resLargestStr += topChar.repeat(topCount);
}
}
return resLargestStr;
};