Valid Parentheses

时间:2014-10-27 14:17:47   收藏:0   阅读:186

典型的用栈(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

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!