20. 有效括号

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
*注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true
  • 自己最初的解法(当时想使用字典值,想着“值”只能是数字,没考虑到也可以是字符)
class Solution:
    def isValid(self, s: str) -> bool:
        lable = "(){}[]"
        if len(s) == 0:
            return True
        
        stack = [s[0]]
        for i in s[1:]:
            if not stack:
                stack.append(i)
                continue
            tmp = stack[-1]
            loc = lable.find(tmp) 
            if (loc + 1) % 2 and loc == (lable.find(i) - 1):
                stack.pop()
            else: stack.append(i)
        
        if stack:
            return False
        return True
class Solution:
    def isValid(self, s: str) -> bool:
        # 字典值查找
        stack = []
        lable = {")":"(","}":"{","]":"["}
        if len(s) == 0:
            return True
        
        for i in s:
            if i == "(" or i == "{" or i == "[":
                stack.append(i)
            elif len(stack) == 0 or lable[i] != stack.pop():
                return False

        return len(stack) == 0
posted @ 2020-04-02 10:22  libbin  阅读(135)  评论(0)    收藏  举报