2
public String reverseParentheses(String s) {3
Stack<String> stack = new Stack<>();6
while (j < s.length()) {8
We need to keep on adding whatever comes9
as long as it is not a ')'.11
if (s.charAt(j) != ')') stack.push(s.charAt(j) + "");14
Now that we have encountered an ')', its time15
to start popping from top of stack unless we find an opening18
then we just need to reverse the string formed by popping19
and put it back on stack.21
Try dry running and it will all make sense24
StringBuilder sb = new StringBuilder();25
while (!stack.isEmpty() && !stack.peek().equals("(")) {26
sb.append(stack.pop());30
stack.push(sb.reverse().toString());36
We have our result string in the stack now,37
we just need to pop it and return the reverse of it.39
StringBuilder res = new StringBuilder();40
while (!stack.isEmpty()) res.append(stack.pop());42
return res.reverse().toString();