Reverse every substring enclosed by matching parentheses, then remove the parentheses from the final result.
Reverse Substrings Between Each Pair of Parentheses
gfgYou are given a string s consisting of lowercase English letters and parentheses ( and ).
Process the string by repeatedly finding any matching pair of parentheses, reversing the substring inside that pair, and removing the parentheses themselves. Nested parentheses should be handled correctly, so inner reversals affect the text that outer pairs later reverse.
Return the final string after all parentheses have been removed and all reversals have been applied.
Input Format
- A single string
s. scontains lowercase letters and the characters(and).
Output Format
- Return the transformed string after reversing the content inside each matching parenthesis pair and removing all parentheses.
Constraints
- The string contains balanced parentheses.
1 <= s.length.scontains only lowercase letters and parentheses.
Example 1
Input
s = "(abcd)"
Output
"dcba"
Explanation
The only parenthesized substring is abcd, which becomes dcba after reversal.
Example 2
Input
s = "(u(love)i)"
Output
"iloveu"
Explanation
First reverse love to get ove l in the inner segment effect, then reverse the outer segment to obtain iloveu after removing parentheses.
Show 1 more example
Example 3
Input
s = "a(bcdefghijkl(mno)p)q"
Output
"apmnolkjihgfedcbq"
Explanation
The inner substring mno becomes onm, and then the larger parenthesized section is reversed with that transformed content.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.