Leetcode 678. Valid Parenthesis String
Given a string s
containing only three types of characters: '('
, ')'
, and '*'
, write a function to check whether the string is valid. The string is valid if:
'('
must have a corresponding right parenthesis ')'
.')'
must have a corresponding left parenthesis '('
.'('
must go before the corresponding right parenthesis ')'
.'*'
could be treated as a single right parenthesis ')'
or a single left parenthesis '('
or an empty string.true
if the string is valid, otherwise return false
.To solve this problem, we’ll use a greedy technique to keep track of the minimum and maximum possible number of open brackets at any point in the string.
min_open
: Tracks the minimum number of unmatched ‘(‘ considering ‘*’ can potentially act as ‘)’.max_open
: Tracks the maximum number of unmatched ‘(‘ considering ‘*’ can potentially act as ‘(‘.Here is the C++ code to solve the problem:
#include <iostream>
#include <string>
class Solution {
public:
bool checkValidString(std::string s) {
int min_open = 0; // Minimum possible open brackets
int max_open = 0; // Maximum possible open brackets
for (auto &ch : s) {
if (ch == '(') {
min_open++;
max_open++;
} else if (ch == ')') {
min_open = std::max(min_open - 1, 0);
max_open--;
} else { // '*' can be '(' or ')' or empty
min_open = std::max(min_open - 1, 0);
max_open++;
}
if (max_open < 0) {
// This means the string can't be valid because we have more closing brackets than opening ones.
return false;
}
}
// At the end of the string, min_open must be zero for the string to be valid.
return min_open == 0;
}
};
// Example usage:
int main() {
Solution sol;
std::string s = "(*))";
bool result = sol.checkValidString(s);
std::cout << (result ? "Valid" : "Invalid") << std::endl;
return 0;
}
min_open
and max_open
.max_open
and increment min_open
unless min_open
is already zero.min_open
(unless it’s zero) and increment max_open
.max_open
becomes less than 0 at any point, return false
because it means there are unmatched closing brackets.min_open
must be zero to ensure all open brackets are matched properly. Return min_open == 0
.s
. This is because we process each character of the string exactly once.This approach ensures that we efficiently check the validity of the string in linear time with constant space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?