leetcode 678. Valid Parenthesis String

678. Valid Parenthesis String
Medium
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:css

Input: "()"
Output: True

 

Example 2:this

Input: "(*)"
Output: True

 

Example 3:spa

Input: "(*))"
Output: True

 

Note:3d

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

大體思路是:自左向右遍歷時, 記錄當前最多能匹配多少右括號(high表示),至少還要匹配多少右括號(low表示)。由於high的數值對後面的右括號還起做用,要維護這一變量,當某一時刻low<0時。說明右括號對於左側過多。*號能根據後面右括號的狀況而變化,遍歷過程當中只要low>=0,就好了。當遍歷到一個左括號是,標誌着它能用於抵消後面的右括號,也標誌着,後面必需要有右括號或*號與其抵消。code

相似只有'(' 和 ')' 的狀況,count分別加減1,看是否最終等於0. 這裏存在*狀況,因此變爲[low, high]blog

時間複雜度O(n),空間複雜度O(1).

three

class Solution {
public:
    bool checkValidString(string s) {
        if (s.size() == 0){
            return true;
        }
        int low = 0, high = 0;
        
       for (int i = 0; i < s.length(); i++) {
            if (s[i] == '(') {
                low++;
                high++;
            } else if (s[i] == ')') {
                if (low > 0) {
                    low--;
                }
                high--;
            } else {
                if (low > 0) {
                    low--;
                }
                high++;
            }
            if (high < 0) {
                return false;
            }
        }
        return low == 0;
    }
};
相關文章
相關標籤/搜索