Given a string consisting of lowercase letters and parentheses, the task is to reverse the substring within each pair of matching parentheses, starting from the innermost one. The final result should exclude the parentheses.
s = "(abcd)"
"dcba"
s = "(u(love)i)"
"iloveu"
Explanation: Reverse the substring "love", then reverse the entire string.
s = "(ed(et(oc))el)"
"leetcode"
Explanation: First, reverse the substring "oc", then reverse "etco", and finally reverse the entire string.
We can solve this problem using a stack to track characters and nested parentheses. Here’s how we can do it:
<?php
// Example 1
echo reverseParentheses("(abcd)") . "\n"; // Output: "dcba"
// Example 2
echo reverseParentheses("(u(love)i)") . "\n"; // Output: "iloveu"
// Example 3
echo reverseParentheses("(ed(et(oc))el)") . "\n"; // Output: "leetcode"
?>
The function reverseParentheses takes a string as input and uses a stack to handle nested parentheses.
Finally, the elements in the stack are concatenated to form the final string. This method efficiently handles nested parentheses and ensures the correct character order after reversing each pair of parentheses content.