Current Location: Home> Latest Articles> Reverse Substrings Between Parentheses - Detailed PHP Implementation

Reverse Substrings Between Parentheses - Detailed PHP Implementation

M66 2025-09-24

Reverse Substrings Between Parentheses

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.

Examples

Input:

s = "(abcd)"

Output:

"dcba"

Example 2:

Input:

s = "(u(love)i)"

Output:

"iloveu"

Explanation: Reverse the substring "love", then reverse the entire string.

Example 3:

Input:

s = "(ed(et(oc))el)"

Output:

"leetcode"

Explanation: First, reverse the substring "oc", then reverse "etco", and finally reverse the entire string.

Constraints

  • s only contains lowercase English letters and parentheses.
  • All parentheses are balanced.

Solution

We can solve this problem using a stack to track characters and nested parentheses. Here’s how we can do it:

  • Iterate through each character of the string.
  • If a left parenthesis "(" is encountered, push it onto the stack.
  • If a right parenthesis ")" is encountered, pop characters from the stack until a left parenthesis "(" is found. Reverse the characters and push them back onto the stack.
  • Finally, concatenate the stack’s contents to get the result string.

PHP Code Example:

<?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"
?>

Explanation

The function reverseParentheses takes a string as input and uses a stack to handle nested parentheses.

  • When a right parenthesis ")" is encountered, characters are popped from the stack until a left parenthesis "(" is found.
  • These popped characters are reversed and pushed back onto the stack.
  • If a character is not a parenthesis, it is simply pushed onto the stack.

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.