LeetCode 20 有效的括号Python3

思路:利用栈遇到右边符号就判断栈里面的最后一个符号否成对,成对pop,不成false

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s)%2 == 1:
            return False
        pushs=list()
        for substr in s:
            if substr=='(' or substr=='[' or substr=='{':
                pushs.append(substr)
            elif pushs:
                if (substr ==')' and pushs[-1]=='(') or (substr==']' and pushs[-1]=='[') or(substr=='}' and pushs[-1]=='{'):
                        pushs.pop()
                else:             
                    return False
            else:
                return False
                
        return not pushs

官方:使用键值对

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s)%2 == 1:
            return False
        
        pairs ={
            ")":"(",
            "]":"[",
            "}":"{"
        }

        pushs=list()
        for substr in s:
            if substr in pairs: # )/]/}
                if not pushs or pairs[substr] != pushs[-1]:
                    return False
                else:
                    pushs.pop()
            else:
                pushs.append(substr)     
        
        return not pushs

猜你喜欢

转载自blog.csdn.net/mxxxkuku/article/details/114445601