Skip to content

Commit a3c9b39

Browse files
authored
Create Solution2.java
1 parent 45bd633 commit a3c9b39

File tree

1 file changed

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

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public String reverseParentheses(String s) {
3+
int n = s.length();
4+
int[] d = new int[n];
5+
Deque<Integer> stk = new ArrayDeque<>();
6+
for (int i = 0; i < n; ++i) {
7+
if (s.charAt(i) == '(') {
8+
stk.push(i);
9+
} else if (s.charAt(i) == ')') {
10+
int j = stk.pop();
11+
d[i] = j;
12+
d[j] = i;
13+
}
14+
}
15+
StringBuilder ans = new StringBuilder();
16+
int i = 0, x = 1;
17+
while (i < n) {
18+
if (s.charAt(i) == '(' || s.charAt(i) == ')') {
19+
i = d[i];
20+
x = -x;
21+
} else {
22+
ans.append(s.charAt(i));
23+
}
24+
i += x;
25+
}
26+
return ans.toString();
27+
}
28+
}

0 commit comments

Comments
 (0)