LeetCode 20 有效的括号---python

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40155090/article/details/83617139

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

有效字符串需满足:

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

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

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

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        lst = []
        for st in s:
            if st == "(" or st == "["or st == "{":
                lst.append(st)
            else:
                if (st == ")" and lst[-1] =="(")\
                    or (st == "]" and lst[-1] =="[")\
                    or (st == "}" and lst[-1] =="{"):
                    lst.pop()
                else:
                    return bool(0)
        ###下面两句可换成 return len(lst)==0
        if len(lst) == 0:
            return bool(1)
        else:
            return bool(0)
        
        
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        #### 键值对正写很麻烦,所以采用下面到写 字典只能通过key找value########
        a = {')':'(', ']':'[', '}':'{'}

        #### l为空l[-1]会出现indexerror,len(l[None])为 ####
        l = [None] 
        for i in s:
            if i in a and a[i] == l[-1]:
                l.pop()
            else:
                l.append(i)
        return len(l)==1
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dic = {')':'(', ']':'[', '}':'{'}
        lst = []
        for st in s:
            if st in dic and len(lst) != 0 and lst[-1]==dic[st]:
                lst.pop()
            elif st in dic and len(lst) != 0 and lst[-1]!=dic[st]:
                return bool(0)
            else:
                lst.append(st)
        return  len(lst)==0

猜你喜欢

转载自blog.csdn.net/qq_40155090/article/details/83617139