leetcode-python-有效的括号

1)栈思路

遇见左括号,则对应右括号入栈

遇右括号:①若栈不为空,则与栈顶比较,相同则continue,不同则返回False

②若栈为空,直接返回False

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s) % 2 == 1:
            return False
        checklist = list()
        for i in s:
            if i == '(':
                checklist.append(')')
            elif i == '[':
                checklist.append(']')
            elif i == '{':
                checklist.append('}')
            else:
                if len(checklist) == 0:
                    return False
                if i == checklist.pop():
                    continue
                else:
                    return False
        if len(checklist) != 0:
            return False
        return True

 

posted @ 2021-06-12 15:30  泊鸽  阅读(74)  评论(0)    收藏  举报