NO.20有效的括号

#利用栈的特性,先进后处,刚好进行比较,{[()]}分别进行比较
class Solution:
    def isValid(self, s: str) -> bool:
        stk = []
        for c in s:
            # 如果c是 ({[ 则入栈
            if c in ['(','[','{']:
                stk.append(c)
            elif c == ')' and stk and stk[-1] == '(': #得判断stack是否为空
                stk.pop();
            elif c == ']' and stk and stk[-1] == '[':
                stk.pop();
            elif c == '}' and stk and stk[-1] == '{':
                stk.pop()
            else:
                return False
        return not stk # 0, 空列表[], 空字典{}, 空元组()都相当于False,not stack表示当stack为空返回true

 

 
posted @ 2022-07-11 17:47  是冰美式诶  阅读(35)  评论(0)    收藏  举报