678. Valid Parenthesis String
Asked at 16Meta39Amazon38Bloomberg36Microsoft35Google32Apple30Oracle35Alibaba100Roku87PornHub87HP75Pwc73TikTok65Salesforce41LinkedIn37Goldman Sachs28
Problem
s contains (, ) and *, where each * can act as (, as ) or as nothing. Decide whether s can be a valid parentheses string.
Example: "(*)" → true; "(*))" → true; ")(" → false
Constraints: length ≤ 100.
Track the range [lo, hi] of possible open counts. ( → both +1; ) → both −1; * → lo−1, hi+1. If hi < 0 fail; clamp lo ≥ 0. Valid iff lo == 0 at the end.
Complexity: O(n) time, O(1) space.
class Solution:
def checkValidString(self, s: str) -> bool:
lo = hi = 0
for ch in s:
if ch == "(":
lo, hi = lo + 1, hi + 1
elif ch == ")":
lo, hi = lo - 1, hi - 1
else:
lo, hi = lo - 1, hi + 1
if hi < 0:
return False
lo = max(lo, 0)
return lo == 0
assert Solution().checkValidString("()") is True
assert Solution().checkValidString("(*)") is True
assert Solution().checkValidString("(*))") is True
assert Solution().checkValidString("(((*)") is False
class Solution {
public boolean checkValidString(String s) {
int lo = 0, hi = 0;
for (char c : s.toCharArray()) {
if (c == '(') { lo++; hi++; }
else if (c == ')') { lo--; hi--; }
else { lo--; hi++; }
if (hi < 0) return false;
lo = Math.max(lo, 0);
}
return lo == 0;
}
}
func checkValidString(s string) bool {
lo, hi := 0, 0 // range of possible open-bracket counts
for i := 0; i < len(s); i++ {
switch s[i] {
case '(':
lo, hi = lo+1, hi+1
case ')':
lo, hi = lo-1, hi-1
default: // '*' is ')', '' or '('
lo, hi = lo-1, hi+1
}
if hi < 0 {
return false
}
lo = max(lo, 0)
}
return lo == 0
}