921. Minimum Add to Make Parentheses Valid #683
-
Topics: A parentheses string is valid if and only if:
You are given a parentheses string
Return the minimum number of moves required to make Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine how many opening or closing parentheses need to be added to make the input string We can solve this problem using a simple counter approach:
Approach:
Let's implement this solution in PHP: 921. Minimum Add to Make Parentheses Valid <?php
/**
* @param String $s
* @return Integer
*/
function minAddToMakeValid($s) {
$balance = 0; // Keeps track of the balance between '(' and ')'
$additions = 0; // Number of additions needed to balance the parentheses
// Iterate through each character of the string
for ($i = 0; $i < strlen($s); $i++) {
if ($s[$i] == '(') {
$balance++; // Increment balance for '('
} else {
$balance--; // Decrement balance for ')'
// If balance goes negative, it means there's an unmatched ')'
if ($balance < 0) {
$additions++; // Add an opening parenthesis
$balance = 0; // Reset balance to 0
}
}
}
// Any remaining positive balance indicates unmatched '('
return $additions + $balance;
}
// Example usage:
$s1 = "())";
echo minAddToMakeValid($s1); // Output: 1
$s2 = "(((";
echo minAddToMakeValid($s2); // Output: 3
?> Explanation:
This solution has a time complexity of O(n) where n is the length of the string, and a space complexity of O(1) since we only use a few variables. |
Beta Was this translation helpful? Give feedback.
We need to determine how many opening or closing parentheses need to be added to make the input string
s
valid. A valid string means that every opening parenthesis'('
has a corresponding closing parenthesis')'
.We can solve this problem using a simple counter approach:
balance
to keep track of the current balance between opening and closing parentheses.additions
to count the minimum number of parentheses required.Approach:
s
.'('
, incrementbalance
by 1.')'
, decrementbalance
by 1:balance
becomes negative, it means there are more closing parentheses than…