-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
40 lines (31 loc) · 773 Bytes
/
main.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
// URL: https://leetcode.com/problems/decode-string/
/**
* @param {string} s
* @return {string}
*/
const decodeString = (s) => {
if (s.length === 1) {
if (Number.isInteger(+s)) return "";
else return s;
}
const stack = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === "]") {
let str = "";
while (true) {
const char = stack.pop();
if (char === "[") break;
str = char + str;
}
let n = "";
while (Number.isInteger(+stack[stack.length - 1])) {
const number = stack.pop();
n = number + n;
}
stack.push(str.repeat(+n));
} else stack.push(s[i]);
}
return stack.join("");
};
console.log(decodeString("3[a]2[bc]"));
console.log(decodeString("3[a2[c]]"));