美文网首页
LeetCode 20 有效的括号 Valid Parenthe

LeetCode 20 有效的括号 Valid Parenthe

作者: 划水型派大星 | 来源:发表于2019-05-07 19:07 被阅读0次

有关栈、堆、队列的LeetCode做题笔记,Python实现

20. 有效的括号 Valid Parentheses

LeetCodeCN 第20题链接

使用 Stack 栈 来操作,用了一个技巧是先做一个字典,key为右括号,value为左括号。

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        mapping = {')':'(', '}':'{', ']':'['}
        for c in s:
            if c not in mapping:
                stack.append(c)
            elif not stack or mapping[c] != stack.pop():
                return False
        return not stack

下一题:703. 数据流中的第K大元素 Kth Largest Element in a Stream

相关文章

网友评论

      本文标题:LeetCode 20 有效的括号 Valid Parenthe

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