Leetcode 1190: Reverse Substrings Between Each Pair of Parentheses

grid47
grid47
Exploring patterns and algorithms
Jul 11, 2024 5 min read

Given a string containing lowercase English letters and balanced parentheses, reverse the substrings enclosed within each pair of parentheses, starting from the innermost ones. After processing, return the resulting string without any parentheses.
Problem
Approach
Steps
Complexity
Input: A single string `s` containing lowercase English letters and parentheses. Parentheses in the string are guaranteed to be balanced.
Example: Input: s = "(xy(z))"
Constraints:
• 1 <= s.length <= 2000
• s only contains lowercase English characters and parentheses.
• All parentheses are guaranteed to be balanced.
Output: A string representing the final processed version of `s` after reversing all substrings enclosed in parentheses and removing the parentheses.
Example: Output: "zyx"
Constraints:
• The output string must not contain any parentheses.
• The order of characters must be correct after processing.
Goal: To reverse substrings enclosed within matching parentheses from the innermost to the outermost and return the processed string without parentheses.
Steps:
• Iterate through the string and process characters.
• Push the indices of opening parentheses onto a stack.
• When encountering a closing parenthesis, reverse the substring from the last opening parenthesis to the current position.
• Remove parentheses and construct the final string.
Goal: The problem has a well-defined input size and structure, ensuring efficient processing.
Steps:
• The input string can be up to 2000 characters long.
• All parentheses in the input string are balanced.
Assumptions:
• The input string always contains balanced parentheses.
• The output string should not contain any parentheses.
Input: Input: s = "(ab(cd))"
Explanation: Reverse the substring "cd" to get "dc". Then reverse the entire substring "abdc" to get "dcba". Remove the parentheses to produce the result "dcba".

Input: Input: s = "a(b(cd)e)f"
Explanation: Reverse "cd" to get "dc". Then reverse "b(dce)" to get "ecd". Combine with the rest of the string to get "aecdfe".

Input: Input: s = "a(b)c"
Explanation: Reverse the substring "b" to get "b". Remove parentheses to produce the result "abc".

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus