1. 程式人生 > >LeetCode 20 有效的括號---python

LeetCode 20 有效的括號---python

給定一個只包括 '('')''{''}''['']' 的字串,判斷字串是否有效。

有效字串需滿足:

  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