1. 程式人生 > >有效的括號(Leetcode第20題)

有效的括號(Leetcode第20題)

方法一:

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        
        if (len(s) % 2 == 1):
            return False
        
        dict_s = {"{":"}", "[":"]", "(":")"}
        stack = []
        
        for i in s: #s中的每一個括號
            if i in dict_s: #如果i在dict_s中,就是判斷左括號在其中
                stack.append(i) #將其放在堆疊中
            else: #如果不在dict_s中,一是不合法和括號,二是右括號
                if not stack or dict_s[stack.pop()] != i: #如果第一個元素就不存在或者順序不對
                    return False
        return stack == []

方法二:

def isValid(s):
    """
    :type s: str
    :rtype: bool
    """

    if (len(s) % 2 == 1):
        return False

    d = {')':'(', ']':'[', '}':'{'}
    stack =[]
    
    for i in s:
        if i in d and d[i] == stack[-1]:
            stack.pop()
        else:
            stack.append(i)
    return stack == []