Construct String With Repeat Limit LeetCode solution in JavaScript

1
var repeatLimitedString = function (s, repeatLimit) {
2
const map = new Map();
3

4
for (const char of s) {
5
const ascii = char.charCodeAt(0) - 97;
6

7
if (!map.has(ascii)) map.set(ascii, 0);
8
map.set(ascii, map.get(ascii) + 1);
9
}
10

11
const maxHeap = new MaxPriorityQueue({ priority: (x) => x[0] });
12

13
map.forEach((count, ascii) => maxHeap.enqueue([ascii, count]));
14

15
let resLargestStr = "";
16

17
while (!maxHeap.isEmpty()) {
18
let [topASCII, topCount] = maxHeap.dequeue().element;
19

20
const topChar = String.fromCharCode(topASCII + 97);
21

22
if (topCount > repeatLimit) {
23
if (maxHeap.isEmpty()) {
24
resLargestStr += topChar.repeat(repeatLimit);
25

26
return resLargestStr;
27
}
28

29
let [secondASCII, secondCount] = maxHeap.dequeue().element;
30
const secondChar = String.fromCharCode(secondASCII + 97);
31

32
resLargestStr += topChar.repeat(repeatLimit);
33
resLargestStr += secondChar;
34

35
topCount -= repeatLimit;
36
secondCount -= 1;
37

38
maxHeap.enqueue([topASCII, topCount]);
39
if (secondCount > 0) maxHeap.enqueue([secondASCII, secondCount]);
40
} else {
41
resLargestStr += topChar.repeat(topCount);
42
}
43
}
44

45
return resLargestStr;
46
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0