Reverse Substrings Between Each Pair of Parentheses Problem
Description
LeetCode Problem 1190.
You are given a string s that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should not contain any brackets.
Example 1:
Input: s = "(abcd)"
Output: "dcba"
Example 2:
Input: s = "(u(love)i)"
Output: "iloveu"
Explanation: The substring "love" is reversed first, then the whole string is reversed.
Example 3:
Input: s = "(ed(et(oc))el)"
Output: "leetcode"
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.
Constraints:
1 <= s.length <= 2000sonly contains lower case English characters and parentheses.- It is guaranteed that all parentheses are balanced.
Solution
Approach: Stack
Inner pairs must be reversed before the outer ones, and a ) always closes the innermost open pair. So we can process the string from left to right with a stack of characters:
- A letter or
(is pushed onto the stack. - At
), pop characters until the matching(. They come off the stack in reverse order, which is exactly the reversal of this pair's content. Drop the(and push the popped characters back in the order they came off.
By the time a pair is closed, every pair inside it has already been closed and reversed, so its content on the stack is already correct. For "(u(love)i)", closing the inner pair turns the stack into ( u e v o l, then the outer ) reverses uevoli into iloveu.
At the end the stack holds only letters, and joining them gives the answer.
Complexity: O(n2) time in the worst case, since each closing parenthesis may move up to n characters (fine for n <= 2000), and O(n) space. There is also an O(n) solution that precomputes the matching parenthesis of each bracket and walks the string, jumping to the partner and flipping direction at every bracket.
class Solution:
def reverseParentheses(self, s: str) -> str:
stack = [] # letters and the '(' that are still open
for ch in s:
if ch == ")":
# Pop back to the matching '(': the letters come off in reverse order.
part = []
while stack[-1] != "(":
part.append(stack.pop())
stack.pop() # the '(' itself
stack.extend(part)
else:
stack.append(ch)
return "".join(stack)