Press "Enter" to skip to content

20.有效的括号

方法一、栈

一、利用栈先入后出的特点,如果遇到左括号入栈,遇到右口号时将对应栈顶左括号出栈,则遍历完所以的括号后stack仍为空。
二、建立哈希表pairs构建左右括号的对应关系。

Python3 代码解释

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s) % 2 == 1:
            return False

        pairs = {
            "}": "{",
            "]": "[",
            ")": "(",
        }
        stack = list()
        for i in s:
            if i in pairs:
                if not stack or stack[-1] != pairs[i]:
                    return False
                stack.pop()
            else:
                stack.append(i)

        return not stack

Source: LeetCode(The title reproduced in this blog is for personal study use only)

Be First to Comment

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注