-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdecode_string.js
51 lines (47 loc) · 1.17 KB
/
decode_string.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
48
49
50
51
//https://leetcode.com/problems/decode-string/
/**
* @param {string} s
* @return {string}
*/
var decodeString = function(s) {
let arr = [];
for (let i = 0; i < s.length; i++) {
let isInteger = Number.isInteger(parseInt(s[i]));
let numberString = "";
while (isInteger) {
isInteger = Number.isInteger(parseInt(s[i + 1]));
numberString = numberString + s[i];
i++;
if (!isInteger) {
arr.push(numberString);
}
}
arr.push(s[i]);
}
let stack = [];
for (let i = 0; i < arr.length; i++) {
const current = arr[i];
if (current === "]") {
let lastElement = stack.shift();
let tempString = lastElement;
while (lastElement !== "[") {
lastElement = stack.shift();
if (lastElement !== "[") {
tempString = lastElement + tempString;
}
}
const number = stack.shift();
const tempOut = tempString
.split("")
.reverse()
.join("")
.repeat(number)
.split(""); //?
stack.unshift(...tempOut);
} else {
stack.unshift(current);
}
}
return stack.reverse().join("");
};
decodeString("100[abc]3[cd]ef"); //?