-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-parenthesis-removal.js
57 lines (54 loc) · 1.5 KB
/
simple-parenthesis-removal.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
52
53
54
55
56
57
/*
Simple Parenthesis Removal
https://www.codewars.com/kata/simple-parenthesis-removal
Given a mathematical expression where the only operators are + or -, return the mathematical expression as a string with the parenthesis removed.
Example: solve("u-(v-w-(x+y))-z"); // returns "u-v+w+x+y-z"
*/
const solve = str => {
let level = 0; obj = {}, prev = '', res = '';
for (let i = 0; i < str.length; i++) {
let current = str[i];
if (current === '(') {
if (str[i - 1] === '-') {
obj[i] = 0;
level++;
}
for (let j in obj) obj[j]++;
prev = current;
continue;
}
if (current === ')') {
for (let j in obj) {
obj[j]--;
if (!obj[j]) {
level--;
delete obj[j];
}
}
prev = current;
continue;
}
if (level % 2) {
if (current === '+') current = '-';
else if (current === '-') current = '+';
}
if (current === '+') {
if (res[res.length - 1] === '+') res = res.slice(0, res.length - 1);
else if (res[res.length - 1] === '-') {
res = res.slice(0, res.length - 1);
if (prev !== '(') current = '-';
}
}
else if (current === '-') {
if (res[res.length - 1] === '+') res = res.slice(0, res.length - 1);
else if (res[res.length - 1] === '-') {
res = res.slice(0, res.length - 1);
if (prev !== '(') current = '+';
}
}
prev = current;
res += current;
}
if (res[0] === '+') res = res.slice(1);
return res;
};