2116. Check if a Parentheses String Can Be Valid #1128
-
|
Topics: A parentheses string is a
You are given a parentheses string
Return Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We can approach it step by step, keeping in mind the constraints and the behavior of the locked positions. Key Points:
Algorithm:
Let's implement this solution in PHP: 2116. Check if a Parentheses String Can Be Valid <?php
/**
* @param String $s
* @param String $locked
* @return Boolean
*/
function canBeValid($s, $locked) {
$n = strlen($s);
// A valid parentheses string must have an even length
if ($n % 2 !== 0) {
return false;
}
// Step 1: Check from left to right
$open = 0; // Tracks possible '(' count
for ($i = 0; $i < $n; $i++) {
// If `locked` is 0, we can treat it as either '(' or ')'
if ($locked[$i] === '0' || $s[$i] === '(') {
$open++;
} else {
// If locked[i] is '1' and s[i] is ')', it reduces the balance
$open--;
}
// At any point, if openBalance is negative, it's invalid
if ($open < 0) {
return false;
}
}
// Step 2: Check from right to left
$close = 0; // Tracks possible ')' count
for ($i = $n - 1; $i >= 0; $i--) {
// If `locked` is 0, we can treat it as either '(' or ')'
if ($locked[$i] === '0' || $s[$i] === ')') {
$close++;
} else {
// If locked[i] is '1' and s[i] is '(', it reduces the balance
$close--;
}
// At any point, if closeBalance is negative, it's invalid
if ($close < 0) {
return false;
}
}
// If both checks pass, the string can be valid
return true;
}
// Example usage:
$s = "))()))";
$locked = "010100";
var_dump(canBeValid($s, $locked)); // Output: bool(true)
$s = "()()";
$locked = "0000";
var_dump(canBeValid($s, $locked)); // Output: bool(true)
$s = ")";
$locked = "0";
var_dump(canBeValid($s, $locked)); // Output: bool(false)
?>Explanation:
Time Complexity:
This solution correctly handles the problem within the given constraints. |
Beta Was this translation helpful? Give feedback.

We can approach it step by step, keeping in mind the constraints and the behavior of the locked positions.
Key Points:
falsebecause a valid parentheses string must have an even length (each opening(needs a closing)).() and closed parentheses ()) as we iterate through the string. If at any point the number of closing parentheses exceeds the number of opening ones, it's impossible to balance the string and we returnfalse.locked[i] == '1') and unlocked (locked[i] == '0'). Unlocked positions allow us to change th…