[勇者闯LeetCode] 20. Valid Parentheses

来源:互联网 发布:校园网络连接 编辑:程序博客网 时间:2024/05/20 06:27

[勇者闯LeetCode] 20. Valid Parentheses

Description

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

Information

  • Tags: Stack | String
  • Difficulty: Easy

Solution

用栈存储需要遇到的右括号。扫描字符串时遇到左括号则其对应的右括号入栈,遇到右括号则出栈并判断两个右括号是否相同,若不相同则返回false。扫描结束后,若栈内还有元素,则返回false

class Solution(object):    def isValid(self, s):        """        :type s: str        :rtype: bool        """        l = {"(": ")", "[": "]", "{": "}"}        ans = []        for x in s:            if x in l:                ans.append(l[x])            elif (len(ans) == 0 or ans.pop() != x):                return False        return False if len(ans) > 0 else True
0 0
原创粉丝点击