[Leetcode] 20. 有效的括号 Python3

 题目:

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

利用栈实现,用字典d = {key1 : value1, key2 : value2 }。代码中的key1 key2 key3分别为左括号,他们的值为对应的右括号。

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s: # s=''时
            return True
        d = {'{': '}', '[': ']', '(': ')'} #字典
        stack = []
        for i in s:
            if i in d:#i={ [ (
                stack.append(i)
            else:
                if not stack or d[stack.pop()] != i:#先遇到右括号 或 出栈的右括号不是i的值
                    return False
        else:
            if stack:
                return False
        return True

猜你喜欢

转载自blog.csdn.net/niceHou666/article/details/81431962