20. Valid Parentheses

2,311次阅读
没有评论

共计 635 个字符,预计需要花费 2 分钟才能阅读完成。

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

An input string is valid if:

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

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

解法

class Solution:
    def isValid(self, s: 'str') -> 'bool':
        
        dict_data={')':'(','}':'{',']':'['}
        left=set(['(','{','['])
        right=set([')','}',']'])
        tmp_list=[]
        for x in s:
            if x in left:
                tmp_list.append(x)
            else:
                tmp=dict_data[x]
                if len(tmp_list)<1 or tmp_list[-1]!=tmp:
                    return False
                tmp_list.pop()
        if tmp_list:
            return False
        
        return True
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2019-02-11发表,共计635字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码