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].

原文:https://leetcode.com/problems/valid-parenthesis-string/solution/

他这个贪心的思路很巧,翻译一下。

算法:

让lo、hi表示匹配到当前位置下,左括号可能出现的最小值与最大值。当前位置是左括号时 (c == '('), then lo++, 否则lo--(lo表示左括号是最少的情况,所以当遇到*号时,认为其均是右括号)。当遇见非右括号时, (c != ')'), then hi++, (hi表示左括号是最多的情况,即认为所有的*号都是左括号)。左括号可能出现的数目区间就是[lo,hi]。左括号最少的数目lo最小是0,而左括号最大的数目hi最小值不能低于0,否则出现以右括号开头的情况。最后合理的匹配应该是存在匹配玩所有位置后,可以出现左括号为0的情况,即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) break;
           lo = Math.max(lo, 0);
       }
       return lo == 0;
    }

猜你喜欢

转载自blog.csdn.net/u013300579/article/details/80059091