20.有效的括号--python

题目:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

法:用栈,遇到左括号就压栈,否则pop栈顶括号,看与当前右括号是否匹配。最后注意判断栈是否为空,不为空的话说明字符串中的左括号比右括号多,字符串无效

def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if s=='':return True
        stk1=[]
        for x in s:
            if x in ['(',"[","{"]:
                stk1.append(x)
            else:
                if stk1==[]:return False
                res=stk1.pop()
                if (x==")" and res!="(") or (x==']' and res!='[')  or x=='}' and res!='{' :return False
                
        return stk1==[]

猜你喜欢

转载自blog.csdn.net/karen17/article/details/88889091