1. 程式人生 > >[leetcode]python3 演算法攻略-有效的括號

[leetcode]python3 演算法攻略-有效的括號

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

有效字串需滿足:

  1. 左括號必須用相同型別的右括號閉合。
  2. 左括號必須以正確的順序閉合。

注意空字串可被認為是有效字串。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if s is None: 
            return False
         
        x = ['[','(','{']
        y = ["]",")","}"]
        z = ["()","[]","{}"]
         
        res = []
        for i in s:
            if i in x:
                res.append(i) # 入棧
            elif i in y:
                # 如果收到一個右括號,但是res中無左括號,直接返回False
                if res == []:
                    return False
                else:
                    temp = res.pop(-1) + i
                    # 其餘情況,出棧一個左括號,判斷左括號+右括號是否有效
                    if temp not in z:
                        return False
        # 如果所有括號對都滿足,但是res還有左括號,返回False
        if len(res) != 0:
            return False
        return True