Medium
LABValid Parenthesis String
Return true if * can be treated as (, ), or empty to make s a valid parentheses string.
EXAMPLES
Example 1
Input
{
"s": "(*)"
}
Output
trueFUNCTION SHAPE
s: string→boolSOLUTION NOTE
Greedy two-pass: first pass treats '*' as '(', second pass treats '*' as ')'. Both must succeed.
Reveal reference solution +
pythonREFERENCE
def checkValidString(self, s: str) -> bool:
def check(s, open_char):
balance = 0
for c in s:
balance += 1 if c == open_char or c == '*' else -1
if balance < 0:
return False
return True
return check(s, '(') and check(s[::-1], ')')Time
O(n)Space
O(1)