-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path394-decode-string.js
More file actions
40 lines (37 loc) · 929 Bytes
/
394-decode-string.js
File metadata and controls
40 lines (37 loc) · 929 Bytes
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 getRepeatedPattern = (pattern, rep) => {
return Array(rep).fill(pattern).join("")
}
/**
* @param {string} s
* @return {string}
*/
var decodeString = function(s) {
const stack = []
let isLastCharNum = false
for(let i=0; i<s.length; i++) {
const c = s[i]
const isCurrCharNum = Number.isInteger(+c)
if(c==="[") {
stack.push(c)
} else if(c==="]") {
let popped = ""
let pattern = ""
while(popped!=="[") {
pattern = popped + pattern
popped = stack.pop()
}
const rep = Number.parseInt(stack.pop(),10)
const repeatedPattern = getRepeatedPattern(pattern, rep)
stack.push(repeatedPattern)
} else {
let toPush = c
if(isCurrCharNum && isLastCharNum) {
const oldNum = stack.pop()
toPush = oldNum+c
}
stack.push(toPush)
}
isLastCharNum = isCurrCharNum
}
return stack.join("")
};