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))
    
相關文章
相關標籤/搜索