String manipulation is a frequent requirement in programming. Handling parentheses and their nested structures, especially reversing substrings within parentheses, can be challenging. This article systematically introduces the problem description, algorithm design, and implementation details for reversing substrings inside every pair of parentheses.
Given a string containing regular characters and parentheses, the goal is to reverse the content inside each pair of parentheses. For example, input "(abc)de(fgh)" should output "cbadehgf". Clear rules and steps allow effective solving of this problem.
The following examples help clarify the problem:
Input: "(xyz)(abc)"
Output: "zyxcba"
Input: "a(bc(de)fg)h"
Output: "ahgfedcba"
The stack data structure is most suitable here because it conveniently manages nested parentheses levels. The overall approach is:
function reverseParentheses($s) {
$stack = [];
$currentString = "";
for ($i = 0; $i < strlen($s); $i++) {
$char = $s[$i];
if ($char === '(') {
array_push($stack, $currentString);
$currentString = "";
} elseif ($char === ')') {
$currentString = strrev($currentString);
if (!empty($stack)) {
$currentString = array_pop($stack) . $currentString;
}
} else {
$currentString .= $char;
}
}
return $currentString;
}
// Example usage
echo reverseParentheses("(abc)de(fgh)"); // Outputs cbadehgf
The time complexity of this method is O(n), where n is the length of the input string, as each character is processed once. Space complexity is also O(n), used by the stack and the current string.
Using a stack to reverse substrings inside parentheses is an efficient solution for this problem. The approach and code provided here are practical references for similar string manipulation tasks in real projects, helping developers improve coding efficiency and problem-solving skills.