Skip to content

Commit ad7c0bd

Browse files
authored
Update Solution2.js
1 parent a3c9b39 commit ad7c0bd

File tree

1 file changed

+23
-24
lines changed
  • solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses

1 file changed

+23
-24
lines changed
Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,32 @@
1-
function reverseParentheses(s) {
2-
const res = [];
1+
/**
2+
* @param {string} s
3+
* @return {string}
4+
*/
5+
var reverseParentheses = function (s) {
36
const n = s.length;
4-
const d = Array(n).fill(-1);
7+
const d = Array(n).fill(0);
58
const stk = [];
6-
7-
for (let i = 0; i < n; i++) {
8-
if (s[i] === '(') stk.push(i);
9-
else if (s[i] === ')') {
9+
for (let i = 0; i < n; ++i) {
10+
if (s[i] === '(') {
11+
stk.push(i);
12+
} else if (s[i] === ')') {
1013
const j = stk.pop();
1114
d[i] = j;
1215
d[j] = i;
1316
}
1417
}
15-
16-
for (let i = 0, forward = true; i < n; ) {
17-
const ch = s[i];
18-
19-
switch (s[i]) {
20-
case '(':
21-
case ')':
22-
i = forward ? d[i] - 1 : d[i] + 1;
23-
forward = !forward;
24-
break;
25-
26-
default:
27-
res.push(ch);
28-
i = forward ? i + 1 : i - 1;
18+
let i = 0;
19+
let x = 1;
20+
const ans = [];
21+
while (i < n) {
22+
const c = s.charAt(i);
23+
if ('()'.includes(c)) {
24+
i = d[i];
25+
x = -x;
26+
} else {
27+
ans.push(c);
2928
}
29+
i += x;
3030
}
31-
32-
return res.join('');
33-
}
31+
return ans.join('');
32+
};

0 commit comments

Comments
 (0)