Leetcode Valid Parentheses 中获取运行时错误解决方案

问题描述 投票:0回答:1

给定一个仅包含字符 '(', ')', '{', '}', '[' 和 ']' 的字符串 s,判断输入字符串是否有效。

输入字符串在以下情况下有效:

左括号必须用相同类型的括号封闭。 左括号必须按正确的顺序关闭。 每个右括号都有一个对应的相同类型的左括号。

示例1:

输入:s =“()” 输出:真 示例2:

输入:s = "()[]{}" 输出:真 例3:

输入:s =“(]” 输出:假

限制:

1 <= s.length <= 104 s consists of parentheses only '()[]{}'.

类解决方案: @静态方法 def isBalanced(s): dict_mapping = {'}': '{', ')': '(', ']': '['} open_stack = []

    for char in s:
        if char in dict_mapping.values():
            open_stack.append(char)
        elif char in dict_mapping.keys():
            if not open_stack or open_stack.pop() != dict_mapping[char]:
                return False
        else:
            # Handle characters other than parentheses, braces, and brackets
            return False

    return len(open_stack) == 0
python-3.x runtime-error
1个回答
0
投票

您应该使用

open_stack[-1]
而不是
open_stack.pop()
如果检查使用了 open_stack.pop(),则左括号将在没有正确检查的情况下被删除

© www.soinside.com 2019 - 2024. All rights reserved.