678. Valid Parenthesis String

Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:

  1. Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  2. Any right parenthesis ')' must have a corresponding left parenthesis '('.
  3. Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  4. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
  5. An empty string is also valid.

Example 1:

Input: "()"
Output: True

Example 2:

Input: "(*)"
Output: True

Example 3:

Input: "(*))"
Output: True

Note:

  1. The string size will be in the range [1, 100].

Rust Solution

struct Solution;

impl Solution {
    fn check_valid_string(s: String) -> bool {
        let mut lo = 0;
        let mut hi = 0;
        for c in s.chars() {
            match c {
                '(' => {
                    lo += 1;
                    hi += 1;
                }
                ')' => {
                    lo = 0.max(lo - 1);
                    hi -= 1;
                }
                _ => {
                    lo = 0.max(lo - 1);
                    hi += 1;
                }
            }
            if hi < 0 {
                return false;
            }
        }
        lo == 0
    }
}

#[test]
fn test() {
    let s = "()".to_string();
    let res = true;
    assert_eq!(Solution::check_valid_string(s), res);
    let s = "(*)".to_string();
    let res = true;
    assert_eq!(Solution::check_valid_string(s), res);
    let s = "(*))".to_string();
    let res = true;
    assert_eq!(Solution::check_valid_string(s), res);
}

Having problems with this solution? Click here to submit an issue on github.