跳过正文
  1. leetcode 题解/

20_有效的括号

·66 字·1 分钟

类型:字符串

    1. 有效的括号 💚

    https://leetcode-cn.com/problems/valid-parentheses/

    ❓ 给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断括号是否合法匹配。

    💡 栈

    左括号压栈,右括号弹栈并比对。

    class Solution:
        def isValid(self, s: str) -> bool:
            if len(s) % 2 == 1:
                return False
    
            pairs = {
                ")": "(",
                "]": "[",
                "}": "{",
            }
            stack = list()
            for ch in s:
                if ch in pairs:
                    if not stack or stack[-1] != pairs[ch]:
                        return False
                    stack.pop()
                else:
                    stack.append(ch)
    
            return not stack

    时间复杂度:O(n),空间复杂度:O(1)