-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathReverse Substrings Between Each Pair of Parentheses.java
47 lines (40 loc) · 1.42 KB
/
Reverse Substrings Between Each Pair of Parentheses.java
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
// Runtime: 6 ms (Top 52.91%) | Memory: 42.5 MB (Top 42.22%)
class Solution {
public String reverseParentheses(String s) {
Stack<String> stack = new Stack<>();
int j = 0;
while(j < s.length()){
/*
We need to keep on adding whatever comes
as long as it is not a ')'.
*/
if(s.charAt(j) != ')')
stack.push(s.charAt(j)+"");
/*
Now that we have encountered an ')', its time
to start popping from top of stack unless we find an opening
parenthesis
then we just need to reverse the string formed by popping
and put it back on stack.
Try dry running and it will all make sense
*/
else{
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty() && !stack.peek().equals("(")){
sb.append(stack.pop());
}
stack.pop();
stack.push(sb.reverse().toString());
}
j++;
}
/*
We have our result string in the stack now,
we just need to pop it and return the reverse of it.
*/
StringBuilder res = new StringBuilder();
while(!stack.isEmpty())
res.append(stack.pop());
return res.reverse().toString();
}
}