You are given a string s made of lowercase English letters and parentheses, and the parentheses are balanced. Reverse the characters inside each matching pair of parentheses, starting from the innermost pair and working outward. Return the resulting string with every parenthesis removed.
Function Signature
def reverse_parentheses(s: str) -> str:
Rules
-
A pair reverses everything between its brackets, including letters that an inner pair has already reversed. Inner pairs are processed before the pairs that enclose them.
-
The returned string contains only letters. An empty pair
()
contributes nothing.
Constraints
-
1 <= len(s) <= 2000
-
s
contains only lowercase English letters and the characters
(
and
)
.
-
All parentheses in
s
are balanced.
Examples
Input: s = "(abcd)"
Output: "dcba"
The only pair encloses abcd, and reversing it gives dcba.
Input: s = "(u(love)i)"
Output: "iloveu"
The inner pair turns love into evol, giving (uevoli). The outer pair then reverses uevoli into iloveu.
Input: s = "a(bcdefghijkl(mno)p)q"
Output: "apmnolkjihgfedcbq"
The inner pair turns mno into onm, giving a(bcdefghijklonmp)q. Reversing bcdefghijklonmp gives pmnolkjihgfedcb, and the letters outside every pair, a and q, stay in place.