📜  门| Gate IT 2007 |问题7(1)

📅  最后修改于: 2023-12-03 14:58:23.731000             🧑  作者: Mango

门 | Gate IT 2007 | 问题7

题目描述

给定一个字符串,字符串中可能包含'(', ')', '{', '}', '[' 和 ']'这六种字符,判断该字符串是否是有效的括号匹配。有效的括号匹配需满足:左括号必须用相同类型的右括号闭合,左括号必须以正确的顺序闭合。

函数签名
def is_valid_parentheses(s: str) -> bool:
    pass
示例
assert is_valid_parentheses("()") == True
assert is_valid_parentheses("()[]{}") == True
assert is_valid_parentheses("(]") == False
assert is_valid_parentheses("([)]") == False
assert is_valid_parentheses("{[]}") == True
解题思路

本题使用栈来解决,先将左括号入栈,然后再遇到右括号时,见其是否与栈顶左括号的类型匹配,如果匹配,则弹出栈顶左括号,否则返回False。

代码实现
def is_valid_parentheses(s: str) -> bool:
    if len(s)%2 == 1:
        return False
    stack = []
    mapping = {")": "(", "}": "{", "]": "["}
    for char in s:
        if char in mapping:
            if not stack or stack.pop() != mapping[char]:
                return False
        else:
            stack.append(char)
    return not stack

时间复杂度:O(n),字符串中的每个字符都需要被压入和弹出一次。

空间复杂度:O(n),需要存储所有的左括号。