LeetCode 20 有效的括号 Valid Parentheses Python

有关栈、堆、队列的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

猜你喜欢

转载自blog.csdn.net/fongim/article/details/89927272
今日推荐