Problem 589
Reverse Substrings Between Each Pair of Parentheses
Medium · 20 pts · String, Stack
Problem
You are given a string of lowercase letters and balanced parentheses. Reverse the text inside each pair of matching parentheses, starting from the innermost pair, and then remove all the parentheses. Print the final string, which contains only letters. A stack of partial strings works: on ( start a new part, on ) reverse the current part and append it to the part below. The input always contains at least one letter.
Input
A single string S of lowercase letters and balanced parentheses.
Output
Print the resulting string of letters.
Constraints
1 <= |S| <= 2000; S has balanced parentheses and at least one letter
Example input
(u(love)i)
Example output
iloveu
Explanation
In (u(love)i), the inner part love is reversed first to evol, giving (uevoli). Reversing that whole part gives iloveu, which is the answer.