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 <= 2000s only contains lower case English characters and parentheses.Utilize a stack to handle the nested or paired parentheses efficiently. By pushing characters onto a stack until a closing parenthesis is encountered, then reversing the needed substring, you can leverage the stack's LIFO properties to achieve the desired result.
This C solution uses an array-based stack to reverse substrings between parenthesis pairs. It iterates through the string, storing characters inside a stack until a closing parenthesis requires a substring reversal. The reversed substring is then pushed back onto the stack, achieving the desired sequence without parentheses.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n).
Space Complexity: O(n) due to the stack usage for storing characters.
This approach involves separately building the result string in a single pass using an auxiliary data structure to track position swaps. The use of local in-string reversals enables an efficient and clean traversal building mechanism.
This C solution divides the task into first creating pair indices for easy traversal and reversal through position swapping, enabling an efficient processing path that aligns with the stack-based idea but applied to index transformations and direct character use.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n).
Space Complexity: O(n), using additional space for parentheses pair tracking and intermediate char arrays.
| Approach | Complexity |
|---|---|
| Stack-Based Approach | Time Complexity: O(n). |
| Two-Pass String Build Approach | Time Complexity: O(n). |
Reverse Substrings Between Each Pair of Parentheses - Leetcode 1190 - Python • NeetCodeIO • 10,740 views views
Watch 9 more video solutions →Practice Reverse Substrings Between Each Pair of Parentheses with our built-in code editor and test cases.
Practice on FleetCode