class Solution:
def reverseParentheses(self, s: str) -> str:
stack = []
for ch in s:
if ch == ')':
temp = []
while stack and stack[-1] != '(':
temp.append(stack.pop())
stack.pop() # Remove the '('
stack.extend(temp)
else:
stack.append(ch)
return ''.join(stack)
class Solution {
public:
string reverseParentheses(string s) {
stack<char> stk;
for (char ch : s) {
if (ch == ')') {
string temp;
while (!stk.empty() && stk.top() != '(') {
temp += stk.top();
stk.pop();
}
stk.pop(); // Remove '('
for (char c : temp) stk.push(c);
} else {
stk.push(ch);
}
}
string result;
while (!stk.empty()) {
result += stk.top();
stk.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
class Solution {
public String reverseParentheses(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
if (ch == ')') {
StringBuilder temp = new StringBuilder();
while (!stack.isEmpty() && stack.peek() != '(') {
temp.append(stack.pop());
}
stack.pop(); // Remove '('
for (char c : temp.toString().toCharArray()) stack.push(c);
} else {
stack.push(ch);
}
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.reverse().toString();
}
}
var reverseParentheses = function(s) {
let stack = [];
for (let ch of s) {
if (ch === ')') {
let temp = [];
while (stack.length > 0 && stack[stack.length - 1] !== '(') {
temp.push(stack.pop());
}
stack.pop(); // Remove '('
for (let c of temp) stack.push(c);
} else {
stack.push(ch);
}
}
return stack.join('');
};
Given a string s
containing lowercase English letters and parentheses, you are to reverse the substrings enclosed within each pair of matching parentheses, starting from the innermost pair. The reversed substrings should replace the original ones, and the final result should not contain any parentheses.
For example, if s = "(u(love)i)"
, the output should be "iloveu"
.
'('
has a corresponding closing parenthesis ')'
.The problem involves reversing substrings defined by nested parentheses, starting from the innermost pair. At first glance, one might consider extracting all substrings between parentheses and reversing them recursively. However, this could get complicated with multiple and nested pairs.
A brute-force approach could involve repeatedly finding the innermost pair of parentheses, reversing the substring, and replacing it in the string until no parentheses remain. However, this would require scanning the string multiple times, leading to inefficiency.
To optimize, we can leverage a stack to process the string in a single pass. Each time we encounter a closing parenthesis, we can pop characters from the stack until the matching opening parenthesis is found, reverse the collected substring, and push the reversed characters back onto the stack. This approach naturally handles nesting and ensures we process from the innermost outwards.
')'
, push it onto the stack.')'
:
'('
is encountered. Collect these characters in a temporary list or string.'('
from the stack (do not include it in the result).
Let's consider the input s = "(u(love)i)"
.
(
: push to stack. Stack: [ '(' ]u
: push to stack. Stack: [ '(', 'u' ](
: push to stack. Stack: [ '(', 'u', '(' ]l
: push to stack. Stack: [ '(', 'u', '(', 'l' ]o
: push to stack. Stack: [ '(', 'u', '(', 'l', 'o' ]v
: push to stack. Stack: [ '(', 'u', '(', 'l', 'o', 'v' ]e
: push to stack. Stack: [ '(', 'u', '(', 'l', 'o', 'v', 'e' ])
: pop until '('. We get 'e', 'v', 'o', 'l' (in that order), reverse is "love". Pop '('.i
: push to stack. Stack: [ '(', 'u', 'e', 'v', 'o', 'l', 'i' ])
: pop until '('. We get 'i', 'l', 'o', 'v', 'e', 'u', reverse is "iloveu". Pop '('."iloveu"
.This demonstrates how the stack naturally handles the innermost parentheses first, building up the result as we process each closing parenthesis.
The key insight is to use a stack to process the string in a single pass, reversing substrings as each closing parenthesis is encountered. This approach elegantly handles nested and multiple parentheses, ensuring efficiency and correctness. The stack structure matches the nesting behavior of the problem, making the solution both intuitive and optimal.