Leetcode 678. Valid Parenthesis String
Given a string s
containing only three types of characters: ‘(‘, ‘)’ and ‘*’, return true
if s
is valid.
The string is considered 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.s
?
s
will be in the range [1, 100]
.To determine if the string s
is valid, we can use a greedy approach. Here’s a concise plan:
low
and high
, representing the possible range of open parentheses.low
and high
.low
and high
.low
(considering it as a ‘)’ to keep the minimum open parentheses as small as possible) and increment high
(considering it as a ‘(‘ to maximize the possibility).low
is greater than 0, it means there are unmatched open parentheses which cannot be made up by any *
. Hence, return false
.high
is non-negative, then it means we managed to balance out the parentheses, thus return true
.This logic ensures that at any point, the number of open parentheses is adjusted keeping the worst scenario in mind using the minimum and maximum bounds (low
and high
).
public class ValidParenthesisString {
public boolean checkValidString(String s) {
int low = 0;
int high = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
low++;
high++;
} else if (c == ')') {
if (low > 0) low--;
high--;
} else { // case '*'
if (low > 0) low--;
high++;
}
if (high < 0) return false; // more ')' than '(' or '*'
}
return low == 0;
}
}
The time complexity of the solution is O(n), where n
is the length of the input string s
. This is because we process each character in the string exactly once.
The space complexity is O(1) since we only use a fixed amount of extra space regardless of the input size (specifically, we use two integer variables).
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?