-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_Simple_string_expansion.js
More file actions
50 lines (41 loc) · 1.48 KB
/
Copy pathstack_Simple_string_expansion.js
File metadata and controls
50 lines (41 loc) · 1.48 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
const str = "k(a3(b(a2(c))))zz"; //"kabaccbaccbacczz"
const stack = [];
let firstBracket = 0,
lastBracket = 0;
const simpleCalc = (data) => {
const splitedData = data.split('').reverse();
let result = '';
splitedData.forEach(item => {
if (Number.isNaN(+item)) {
result = result + item;
} else {
let intermediateResult = '';
for (let i = 1; i <= item; i++) {
intermediateResult = intermediateResult + result;
}
result = intermediateResult;
}
});
return result.split('').reverse().join('');
};
const calculate = (input) => {
stack.push(input);
firstBracket = stack[stack.length - 1].indexOf('(');
lastBracket = stack[stack.length - 1].lastIndexOf(')');
while(firstBracket && lastBracket !== -1) {
stack.push(stack[stack.length - 1].slice(firstBracket + 1, lastBracket));
firstBracket = stack[stack.length - 1].indexOf('(');
lastBracket = stack[stack.length - 1].lastIndexOf(')');
}
let res = simpleCalc(stack.pop());
while(stack.length > 0) {
firstBracket = stack[stack.length - 1].indexOf('(');
lastBracket = stack[stack.length - 1].lastIndexOf(')');
res = simpleCalc(`${stack[stack.length - 1]
.slice(0, firstBracket)}${res}${stack[stack.length - 1]
.slice(lastBracket + 1)}`);
stack.pop();
}
return res;
};
console.log(calculate('k(a3(b(a2(c))))zz'));