Reverse Substrings Between Each Pair of Parentheses — LeetCode 1190 Python Solution
- Problem
- #1190
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- s = "(abcd)"
- Output
- "dcba"
Python solution
class Solution:
def reverseParentheses(self, s: str) -> str:
stk = []
for c in s:
if c == ")":
t = []
while stk[-1] != "(":
t.append(stk.pop())
stk.pop()
stk.extend(t)
else:
stk.append(c)
return "".join(stk)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n), where n is the length of the string s auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses?
- LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses?
- The Python solution on this page uses O(n), where n is the length of the string s auxiliary space.
- What topics does LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses cover?
- LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses is tagged Stack and String on LeetCode.