码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Parentheses

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

标签:style   blog   io   color   ar   sp   div   on   问题   

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

标签:style   blog   io   color   ar   sp   div   on   问题   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!