678. Valid Parenthesis String¶
Description¶
Given a string s
containing only three types of characters: '('
, ')'
and '*'
, return true
if s
is valid.
The following rules define a valid string:
- Any left parenthesis
'('
must have a corresponding right parenthesis')'
. - Any right parenthesis
')'
must have a corresponding left parenthesis'('
. - 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""
.
Example 1
- Input:
s = "()"
- Output:
true
Example 2
- Input:
s = "(*)"
- Output:
true
Example 3
- Input:
s = "(*))"
- Output:
true
Constraints
1 <= s.length <= 100
s[i]
is'('
,')'
or'*'
.
Solution: Greedy Approach¶
- Time Complexity:
O(n)
, wheren
is the length of the strings
. - Space Complexity:
O(1)
There are two conditions in which the string is unbalanced
- We encounter too many
')'
- In the end, we still have some
'('
which didn't find their matching')'
Why does we need openMin = Math.max(openMin, 0)
?
openMin
will be subtracted by 1, whenever we encounter either ')'
or '*'
. However, if we just ignore the '*'
as empty strings. Eg,
Both "() "
and "()))"
will be matched, but since we ignored empty string, "()))"
will be the final result, which is not correct. Hence if we make openMin
become 0
, and it become nothing similar to ''
empty string definition and neither '('
nor ')'
will be added.12