Skip to content

Commit bcd8786

Browse files
authored
Update Solution2.ts
1 parent 91a21cc commit bcd8786

File tree

1 file changed

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

1 file changed

+17
-22
lines changed
Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,28 @@
11
function reverseParentheses(s: string): string {
2-
const res: string[] = [];
32
const n = s.length;
4-
const d = Array(n).fill(-1);
3+
const d: number[] = Array(n).fill(0);
54
const stk: number[] = [];
6-
7-
for (let i = 0; i < n; i++) {
8-
if (s[i] === '(') stk.push(i);
9-
else if (s[i] === ')') {
5+
for (let i = 0; i < n; ++i) {
6+
if (s[i] === '(') {
7+
stk.push(i);
8+
} else if (s[i] === ')') {
109
const j = stk.pop()!;
1110
d[i] = j;
1211
d[j] = i;
1312
}
1413
}
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;
14+
let i = 0;
15+
let x = 1;
16+
const ans: string[] = [];
17+
while (i < n) {
18+
const c = s.charAt(i);
19+
if ('()'.includes(c)) {
20+
i = d[i];
21+
x = -x;
22+
} else {
23+
ans.push(c);
2924
}
25+
i += x;
3026
}
31-
32-
return res.join('');
27+
return ans.join('');
3328
}

0 commit comments

Comments
 (0)