首页 > 代码库 > Valid Parentheses

Valid Parentheses

典型的用栈(stack)结构解决问题的例子

class Solution:    def isPair(self,s1,s2):        if (s1==( and s2==))or (s2==( and s1==)):            return True        if (s1==[ and s2==])or (s2==[ and s1==]):            return True        if (s1=={ and s2==})or (s2=={ and s1==}):            return True        else :            return False                def isValid(self, s):        if s=="":            return True                pair_right=set([),],}])        if s[0] in pair_right :            return False        len_s=len(s)        if len_s%2==1:            return False                i=1;        stack=[s[0]]        while(i<len_s):            stack.append(s[i])            len_stack=len(stack)            if len_stack>1:                if self.isPair(stack[len_stack-1],stack[len_stack-2]):                    stack.pop()                    stack.pop()                else:                    pass            i+=1        len_stack=len(stack)        if len(stack)==0:            return True        else:            return False

 

Valid Parentheses