Leetcode 20. 有效的括号

心路历程:

看到括号问题直接想到栈,但是纠结了一下题目中给出的 '2. 左括号必须以正确的顺序闭合' 这一约束,其实这句话的意思简化了题目要求,'()'这样的字符串就不满足要求了。

注意的点:

1、注意最后需要栈为空的时候才能返回true,否则代表左括号可能会多余。

解法:栈

python 复制代码
class Solution:
    def isValid(self, s: str) -> bool:
        # 栈
        from collections import deque
        stack = deque([])
        lefts, rights = ['(', '[', '{'], [')', ']', '}']
        mappings_right = {')':'(', ']':'[', '}':'{'}
        for c in s:
            if c in lefts:
                stack.append(c)
            else:
                if len(stack) == 0: return False
                if stack.pop() != mappings_right[c]: return False
        if len(stack) == 0: return True
        else: return False
相关推荐
非优秀程序员10 小时前
第05章 播放器大战,暴风、快播与那一夜|《互联网产品恩仇录》
算法
文丑颜不良啊12 小时前
LeetCode2481~2500题目解析
java·leetcode
武子康16 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
文丑颜不良啊19 小时前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊20 小时前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊21 小时前
LeetCode2521~2540题目解析
java·leetcode
lisw051 天前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术1 天前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs1 天前
Rust LeetCode238 算法题解
开发语言·算法·rust