1
class Solution {
2
public String reverseParentheses(String s) {
3
Stack<String> stack = new Stack<>();
4

5
int j = 0;
6
while (j < s.length()) {
7
/*
8
We need to keep on adding whatever comes
9
as long as it is not a ')'.
10
*/
11
if (s.charAt(j) != ')') stack.push(s.charAt(j) + "");
12

13
/*
14
Now that we have encountered an ')', its time
15
to start popping from top of stack unless we find an opening
16
parenthesis
17

18
then we just need to reverse the string formed by popping
19
and put it back on stack.
20

21
Try dry running and it will all make sense
22
*/
23
else {
24
StringBuilder sb = new StringBuilder();
25
while (!stack.isEmpty() && !stack.peek().equals("(")) {
26
sb.append(stack.pop());
27
}
28

29
stack.pop();
30
stack.push(sb.reverse().toString());
31
}
32
j++;
33
}
34

35
/*
36
We have our result string in the stack now,
37
we just need to pop it and return the reverse of it.
38
*/
39
StringBuilder res = new StringBuilder();
40
while (!stack.isEmpty()) res.append(stack.pop());
41

42
return res.reverse().toString();
43
}
44
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0