Valid Parenthesis String

medium string stack greedy

Problem

Given a string s containing only '(', ')' and '*', return true if s is valid. '*' can be treated as '(', ')', or the empty string.

Inputs = "(*))"
Outputtrue
Treat '*' as '(' to get "(())", which is balanced.

def check_valid_string(s):
    lo = hi = 0
    for c in s:
        lo += 1 if c == '(' else -1
        hi += 1 if c != ')' else -1
        if hi < 0:
            return False
        lo = max(lo, 0)
    return lo == 0
function checkValidString(s) {
  let lo = 0, hi = 0;
  for (const c of s) {
    lo += c === '(' ? 1 : -1;
    hi += c !== ')' ? 1 : -1;
    if (hi < 0) return false;
    if (lo < 0) lo = 0;
  }
  return lo === 0;
}
class Solution {
    public boolean checkValidString(String s) {
        int lo = 0, hi = 0;
        for (char c : s.toCharArray()) {
            lo += c == '(' ? 1 : -1;
            hi += c != ')' ? 1 : -1;
            if (hi < 0) return false;
            lo = Math.max(lo, 0);
        }
        return lo == 0;
    }
}
bool checkValidString(string s) {
    int lo = 0, hi = 0;
    for (char c : s) {
        lo += c == '(' ? 1 : -1;
        hi += c != ')' ? 1 : -1;
        if (hi < 0) return false;
        lo = max(lo, 0);
    }
    return lo == 0;
}
Time: O(n) Space: O(1)