leetcode20:有效的括号


思想
1.定义一个列表valid存放着每对有效符号
2.将字符串s中的字符放入stack
3.判断stack的长度是否大于等于2并且stack[-2]+stack[-1]是否在valid中。若是则跳转4,否则跳转2
4.将stack[-1]和stack[-2]删除,并跳转2

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        valid =['()','[]','{}']
        for i in range(0,len(s)):
            stack.append(s[i])
            if len(stack)>=2 and stack[-2]+stack[-1] in valid:
                stack.pop()
                stack.pop()
        return len(stack)==0

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/82807193
今日推荐