跳至主要內容

Leetcode 678. Valid Parenthesis String

Given a string s containing only three types of characters: '('')' and '*', return true if s is valid.

The following rules define a valid string:

  • Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  • Any right parenthesis ')' must have a corresponding left parenthesis '('.
  • Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  • '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "(*)"
Output: true

Example 3:

Input: s = "(*))"
Output: true

Constraints:

  • 1 <= s.length <= 100
  • s[i] is '('')' or '*'.

This question can be solved by using stack.

The idea is pairing valid parentheses first, then check if star sign can make up those invalid parentheses.

class Solution:
    def checkValidString(self, s: str) -> bool:
        star_positions = []
        open_parentheses = []

        for i in range(len(s)):
            if s[i] == '(':
                open_parentheses.append(i)
            elif s[i] == '*':
                star_positions.append(i)
            else:
                if open_parentheses:
                    open_parentheses.pop()
                elif star_positions:
                    star_positions.pop()
                else:
                    return False
        
        while open_parentheses and star_positions:
            open_index = open_parentheses.pop()
            star_index = star_positions.pop()

            if star_index < open_index:
                return False
        
        return False if open_parentheses else True
分類:LeetcodeStack

搶先發佈留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

由 Compete Themes 設計的 Author 佈景主題