20. Valid Parentheses

1.题目:app

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.spa

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.code

这个题目不难理解,就是咱们平时写程序时候,小括号,中括号,大括号都要对应的包起来,不然就有问题。blog

如今给定一个字符串,须要你来判断一下这个字符串是否知足该要求!utf-8

2.代码:rem

该问题,用栈的后进先出结构就很容易解决了。分三种状况,1. 下一个元素是左边的,直接入栈;2.下一个元素是右边的,要看可否和栈顶元素匹配,不匹配固然有问题了;3.匹配的话,恰好抵消掉栈顶元素,栈顶元素出栈;最后,判断下栈有没有彻底抵消便可。字符串

# -*-coding:utf-8-*-
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        left = ['(','[','{']
        right = [')',']','}']
        l = list(s)
        stack = []
        left_count,right_count = 0,0
        #从左到右遍历字符串
        while len(l)>0:
            #若是这个字符是在left中,就写进stack
            if l[0] in left:
                stack.append(l[0])
            #若是这个字符在right中,先判断stack,若是stack为空,直接返回False,若是stack的最后一位和该字符不匹配(不然会出现交叉状况,例如([)]),也直接返回False
            #若是stack的最后一位和该字符恰好匹配,则从stack中弹出匹配到的字符
            elif l[0] in right:        
                if len(stack)==0:return False
                #print (l[0],'  ',stack[-1])
                #print (right.index(')'))
                if right.index(l[0])==left.index(stack[-1]):
                    stack.pop()
                else:
                    return False
            #若是输入不是这些,也返回False,题目中说了 just the characters,只有这六个字符
            else:
                return False
            l.remove(l[0])
        #最后判断stack是否恰好抵消
        return len(stack)==0
                
            
        
if __name__=='__main__':
    s = '(('
    a = Solution()
    print (a.isValid(s))
    
相关文章
相关标签/搜索