678. Valid Parenthesis String #170
-
Topics: Given a string The following rules define a valid string:
Example 1: Input: Example 2: Input: Example 3: Input: Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a greedy approach with two counters to track the possible minimum and maximum number of open parentheses Key Idea:
Let's implement this solution in PHP: 678. Valid Parenthesis String <?php
function checkValidString($s) {
$minOpen = 0; // Minimum number of open parentheses
$maxOpen = 0; // Maximum number of open parentheses
// Iterate through the string
for ($i = 0; $i < strlen($s); $i++) {
if ($s[$i] == '(') {
// Treat '(' as an open parenthesis
$minOpen++;
$maxOpen++;
} elseif ($s[$i] == ')') {
// Treat ')' as closing a parenthesis
$minOpen = max(0, $minOpen - 1); // Ensure minOpen doesn't go below 0
$maxOpen--;
} else {
// Treat '*' as both opening '(' and closing ')' or an empty string ""
$minOpen = max(0, $minOpen - 1); // Consider '*' as ')'
$maxOpen++; // Consider '*' as '('
}
// If at any point maxOpen becomes negative, it's invalid
if ($maxOpen < 0) {
return false;
}
}
// In the end, minOpen should be 0 for the string to be valid
return $minOpen == 0;
}
// Test cases
echo checkValidString("()") ? "true" : "false"; // Output: true
echo "\n";
echo checkValidString("(*)") ? "true" : "false"; // Output: true
echo "\n";
echo checkValidString("(*))") ? "true" : "false"; // Output: true
?> Explanation:
Time Complexity:
Space Complexity:
Output:
|
Beta Was this translation helpful? Give feedback.
We can use a greedy approach with two counters to track the possible minimum and maximum number of open parentheses
(
that could be valid at any point in the string.Key Idea:
We maintain two counters:
minOpen
andmaxOpen
.minOpen
: Tracks the minimum number of open parentheses that could still be valid.maxOpen
: Tracks the maximum number of open parentheses that could still be valid.As we iterate through the string:
'('
, we increment bothminOpen
andmaxOpen
since we have one more possible open parenthesis.')'
, we decrement bothminOpen
andmaxOpen
since we close one open parenthesis.'*'
, we incr…