首页 > 其他 > 详细

Valid Parentheses

时间:2014-10-27 14:17:08      阅读:261      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/iois/p/4054018.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!