[勇者闯LeetCode] 20. Valid Parentheses

    xiaoxiao2021-03-25  88

    [勇者闯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 | StringDifficulty: 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
    转载请注明原文地址: https://ju.6miu.com/read-25655.html

    最新回复(0)