美文网首页
leetcode20 Valid Parentheses

leetcode20 Valid Parentheses

作者: 就是果味熊 | 来源:发表于2020-07-01 20:50 被阅读0次

原题链接 https://leetcode.com/problems/valid-parentheses/

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false

括号匹配有先进后出的特征,这里用栈对其进行匹配确认。字符可能属于括号,也可能不属于,各种情况都要考虑到。

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s) & 1 == 1:
            return False
        dicts = {"(":")", "{":"}", "[":"]"}
        stack = []
        
        for i in range(len(s)):
            if s[i] in "([{":
                stack.append(s[i])
            elif s[i] in "}])":
                if stack and dicts[stack[-1]] == s[i]:
                    stack.pop()
                else:
                    return False
            else:
                return False
        return not stack
                

相关文章

网友评论

      本文标题:leetcode20 Valid Parentheses

      本文链接:https://www.haomeiwen.com/subject/akzhqktx.html