ericpuwang

有效的括号

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

给定一个只包括(){}[]的字符串s,判断字符串是否有效。

有效字符串需满足:

示例1

输入:s = "()"
输出:true

示例2

输入:s = "()[]{}"
输出:true

示例3

输入:s = "(]"
输出:false

示例4

输入:s = "([])"
输出:true

示例5

输入:s = "([)]"
输出:false

提示

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for item in s:
            if len(stack) == 0:
                stack.append(item)
                continue
            if item == ')' and stack[-1] == '(':
                stack = stack[:-1]
            elif item == '}' and stack[-1] == '{':
                stack = stack[:-1]
            elif item == ']' and stack[-1] == '[':
                stack = stack[:-1]
            else:
                stack.append(item)
        return len(stack) == 0