-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseSubstringsBetweenEachPairOfParentheses1190.java
More file actions
38 lines (31 loc) · 1.28 KB
/
ReverseSubstringsBetweenEachPairOfParentheses1190.java
File metadata and controls
38 lines (31 loc) · 1.28 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
import java.util.*;
public class ReverseSubstringsBetweenEachPairOfParentheses1190 {
/*
* You are given a string s that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should not contain any brackets.
*/
class Solution {
public String reverseParentheses(String s) {
Stack<Integer> stack = new Stack<>() ;
StringBuilder sb = new StringBuilder();
int i = 0 ;
for (char c : s.toCharArray()) {
if (c == '(') stack.push(sb.length());
else if (c == ')') {
int start = stack.pop();
reverse(sb, start, sb.length()-1);
}
else sb.append(c);
}
return sb.toString();
}
public void reverse(StringBuilder s , int start , int end) {
while (start < end) {
char temp = s.charAt(start);
s.setCharAt(start++, s.charAt(end));
s.setCharAt(end--, temp);
}
}
}
}