簡體   English   中英

是什么導致了leetcode問題中的這個錯誤

[英]What is causing this error in leetcode problem

我正在解決一個簡單的問題,但在解決"()[]{}"時出現此錯誤。

給定一個僅包含字符 '(', ')', '{', '}', '[' 和 ']' 的字符串 s,確定輸入字符串是否有效。

輸入字符串在以下情況下有效:

開括號必須用相同類型的括號閉合。 開括號必須以正確的順序閉合。

class Solution:
    def isValid(self, s: str) -> bool:
        matchdict = {'(': ')', '{': '}', '[': ']'}
        slen = len(s)
        if slen%2!=0:
            return False
        
        for i in range(slen // 2):
            if (matchdict[s[i]] != s[slen-i-1] and (matchdict[s[2*i]] != s[2*i+1])):
                return False
        
        
        return True
KeyError: ')'
    if (matchdict[s[i]] != s[slen-i-1] and (matchdict[s[2*i]] != s[2*i+1])):
Line 9 in isValid (Solution.py)
    ret = Solution().isValid(param_1)
Line 32 in _driver (Solution.py)
    _driver()
Line 43 in <module> (Solution.py)

您的代碼假設在右括號后不會打開任何內容。 正如您的簡單示例所示,字符串不一定是對稱的。 另一個簡單的例子是(())()之類的。

這個問題需要一個堆棧,因為您需要跟蹤可能無限數量的混合括號。 如果您只有一種類型的括號,則計數器足以驗證字符串。 在 python 中,您可以使用list或稍微更有效的collections.deque來跟蹤堆棧。

from collections import deque

close_brackets = {']': '[', ')': '(', '}': '{'}
open_brackets = set(close_brackets.values())

def check(s):    
    stack = deque()
    for c in s:
        if c in open_brackets:
            stack.append(c)
        elif c in close_brackets:
            if not stack or stack.pop() != close_brackets[c]:
                return False
    # If the stack is not empty, you have an unmatched parenthesis
    # somewhere. `not` will convert the result to bool for you.
    return not stack

作為額外的獎勵,這個解決方案將跳過任何非括號字符,以防你想用它來驗證數學或類似的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM