-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path394.decode-string.js
More file actions
42 lines (41 loc) · 1.09 KB
/
Copy path394.decode-string.js
File metadata and controls
42 lines (41 loc) · 1.09 KB
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
/**
* @param {string} s
* @return {string}
*/
var decodeString = function(s) {
let tempNumArr = [];
let number = [];
let string = [];
for (let i = 0; i < s.length; i++) {
// if is number, push to temp number array
if (s[i].match(/\d/)) {
tempNumArr.push(s[i]);
} else {
// if not number, first clean up temp number arr , and push a number
if (tempNumArr.length > 0) {
number.push(tempNumArr.join(""));
tempNumArr = [];
}
// then, if is ], pop until [
if (s[i].match(/\]/)) {
let tempStr = "";
let current = string.pop();
while (!current.match(/\[/)) {
tempStr = current + tempStr;
current = string.pop();
}
// use the last number in number stack
let tempNumToNum = Number(number.pop());
//Reproduce the string
while (tempNumToNum > 0) {
string.push(tempStr);
tempNumToNum--;
}
} else {
string.push(s[i]);
}
}
}
return string.join("");
};
//The Magic Of Stack is the it can find the nearest operation