-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode-string.ts
40 lines (36 loc) · 1.02 KB
/
decode-string.ts
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
const DIGITS = {
"1": true,
"2": true,
"3": true,
"4": true,
"5": true,
"6": true,
"7": true,
"8": true,
"9": true,
"0": true,
};
export function decodeString(s: string): string {
if (s.length === 0) {
return "";
}
if (!(s[0] in DIGITS)) {
return s[0] + decodeString(s.slice(1));
}
let startIndex = 0;
let digitBuffer: string[] = [];
for (; s[startIndex] in DIGITS; ++startIndex) {
digitBuffer.push(s[startIndex]);
}
let repeatCount = digitBuffer.reduce((acc, cur): number => acc * 10 + Number(cur), 0);
let endIndex = startIndex + 1;
for (let numOpenBrackets = 1; numOpenBrackets !== 0; ++endIndex) {
if (s[endIndex] === "[") {
++numOpenBrackets;
} else if (s[endIndex] === "]") {
--numOpenBrackets;
}
}
let repeatSlice = s.slice(startIndex + 1, endIndex - 1);
return new Array(repeatCount).fill(decodeString(repeatSlice)).join("") + decodeString(s.slice(endIndex));
}