美文网首页
【Leetcode】020-Valid-Parentheses

【Leetcode】020-Valid-Parentheses

作者: FLYNNNOTES | 来源:发表于2018-10-08 21:16 被阅读0次

Qustion

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

An input string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.

tips: Stack:first in last out

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        d = {')':'(', '}':'{', ']':'['}
        
        stack = []
        
        for i in s:
            if i in d and len(stack)!=0 and d[i]==stack[-1]:
                stack.pop()
            else:
                stack.append(i)
        
        return len(stack)==0

相关文章

网友评论

      本文标题:【Leetcode】020-Valid-Parentheses

      本文链接:https://www.haomeiwen.com/subject/tfqsaftx.html