This repository was archived by the owner on Jun 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq2.js
More file actions
70 lines (63 loc) · 1.27 KB
/
Copy pathq2.js
File metadata and controls
70 lines (63 loc) · 1.27 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const decodeString = s => {
const stack = [];
let temp = ''
for (let i = 0; i < s.length; i++) {
// if a number
if (!isNaN(s[i])) {
if (isNaN(temp)) {
stack.push(temp);
temp = '';
}
temp += s[i]
}
else if (s[i] === '[') {
if (temp) {
stack.push(temp)
temp = ''
}
}
else if (s[i] === ']') {
if (temp) {
stack.push(temp)
temp = ''
}
const str = stack.pop()
const num = stack.pop()
if (!isNaN(num)) {
stack.push(multiplyString(str, num))
} else {
stack.push(num+str)
}
}
else {
if (!isNaN(temp) && temp) {
stack.push(temp)
temp = ''
}
temp += s[i]
}
}
if (temp) {
stack.push(temp)
}
return formatStack(stack);
}
const multiplyString = (str, num) => {
let productString = '';
for (let i = 0; i < num; i++) {
productString += str;
}
return productString;
}
const formatStack = stack => {
while (stack.length > 1) {
const lastEl = stack.pop();
const secondLastEl = stack.pop();
if (!isNaN(secondLastEl)) {
stack.push(multiplyString(lastEl, secondLastEl))
} else {
stack.push(secondLastEl + lastEl)
}
}
return stack.pop()
}