Skip to content

Instantly share code, notes, and snippets.

@shanecandoit
Created July 11, 2024 15:55
Show Gist options
  • Save shanecandoit/d5b7a7d93ac88d0d8a014c74d3848ed6 to your computer and use it in GitHub Desktop.
Save shanecandoit/d5b7a7d93ac88d0d8a014c74d3848ed6 to your computer and use it in GitHub Desktop.
1190. Reverse Substrings Between Each Pair of Parentheses
class Solution:
def reverseParentheses(self, s: str) -> str:
""" Reverse Substrings Between Each Pair of Parentheses
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.
"""
stack = []
for c in s:
if c == ')':
sub = []
while stack[-1] != '(':
sub.append(stack.pop())
stack.pop() # remove '('
stack.extend(sub)
else:
stack.append(c)
return ''.join(stack)
assert Solution().reverseParentheses("(abcd)") == "dcba"
assert Solution().reverseParentheses("(u(love)i)") == "iloveu"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment