1190. Reverse Substrings Between Each Pair of Parentheses #221
-
Topics: You are given a string Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here's the step-by-step plan:
Here's the implementation in PHP: 1190. Reverse Substrings Between Each Pair of Parentheses <?php
function reverseParentheses($s) {
$stack = [];
// Traverse each character in the string
for ($i = 0; $i < strlen($s); $i++) {
if ($s[$i] == ')') {
$temp = '';
// Pop from stack until an opening parenthesis is found
while (end($stack) != '(') {
$temp .= array_pop($stack);
}
// Pop the opening parenthesis
array_pop($stack);
// Push the reversed substring back to the stack
for ($j = 0; $j < strlen($temp); $j++) {
array_push($stack, $temp[$j]);
}
} else {
// Push current character to the stack
array_push($stack, $s[$i]);
}
}
// Concatenate the stack to form the result string
return implode('', $stack);
}
// 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
This method efficiently handles nested parentheses and ensures the correct order of characters after reversing the substrings within each pair of parentheses. |
Beta Was this translation helpful? Give feedback.
Here's the step-by-step plan:
Here's the implementation in PHP: 1190. Reverse Substrings Between Each Pair of Parentheses