【leetcode❤python】 20. Valid Parentheses

#-*- coding: UTF-8 -*-
#利用栈的思想
#如果输入的左测扩则入栈,如果输入为右侧扩,判断其是否与当前栈顶配对,如果匹配则删除这一对,否则return False
#'(', ')', '{', '}', '[' and ']'
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        left_tag=['(','{','[']
        right_tag=[')','}',']']
        stack_list=[]
        match_dic={'(':')','{':'}','[':']'}
        for i in range(len(s)):
            curcheck=s[i]
            if left_tag.__contains__(curcheck):
                stack_list.append(curcheck)
            elif right_tag.__contains__(curcheck):
                if  len(stack_list)!=0 and match_dic.get(stack_list[-1])==curcheck:
                    stack_list.pop()
                else:
                    return False
            else:return False
        
        return True if len(stack_list)==0 else False
    
sol=Solution()
print sol.isValid('[')

原文地址:https://www.cnblogs.com/kwangeline/p/6059546.html