Problem Description
Given a string s containing lower-case English letters and balanced parentheses, reverse the substrings contained within each pair of matching parentheses, starting from the innermost pair. The final output should not include any parentheses.
Key Insights
- Use a stack to keep track of the substrings before encountering a parenthesis.
- When an opening bracket '(' is encountered, push the current working substring onto the stack and reset it.
- When a closing bracket ')' is encountered, reverse the current substring and then append it to the substring obtained from the top of the stack.
- This approach naturally handles nested parentheses by processing the innermost substring first.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(n), due to the use of a stack to store intermediate substring states.
Solution
We solve the problem by iterating through the string character by character. We maintain a "current" container (using a list or similar structure) to build the substring under processing. When encountering an opening parenthesis, we push the current substring onto a stack and reset it for building the new substring. When we encounter a closing parenthesis, we reverse the current substring, then pop the previous substring state from the stack and concatenate the reversed substring to it. This method ensures that nested parentheses are correctly handled, and at the end, we obtain a string without any remaining parentheses.