繁体   English   中英

无法在 Python 中增加变量

[英]Cannot increment variable in Python

我正在学习如何编码,希望得到任何输入。 这是我为解决 Leetcode 上的一个简单问题而编写的代码。

问题是当第一次dict_ab[deck[-1]] == s[i+1],执行deck.pop()之后,它会迭代i到i+=2。 然而,这并没有发生,我自动只+=1。 我做错了什么? 我已经为此工作了一整天,无法弄清楚。

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        a = ('(','{','[')
        b = (')','}',']')
        dict_ab = dict(zip(a,b))

        import collections

        if (len(s) % 2 == 1) or (len(s) == 0):
            return False
        else:
            deck = collections.deque()
            #deck.append(s[0])
            #print(s[0])
            #print(len(s))
            for i in range(0, len(s), 1):
                #print(i)
                deck.append(s[i])
                #print(deck)

                if dict_ab[deck[-1]] == s[i+1]:
                    deck.pop()
                    #print(deck)
                    i +=2
                elif dict_ab[deck[-1]] != s[i+1]:
                    deck.append(s[i])
                    i +=1


            if len(deck) > 0:
                return False

        return True


    s = ('()[]')
    result = Solution().isValid(s)
    print(result)

我看到的结果如下:

 KeyError Traceback (most recent call last) <ipython-input-9-56d864c71658> in <module>() 37 return True 38 s = ('()[]') ---> 39 result = Solution().isValid(s) 40 print(result) <ipython-input-9-56d864c71658> in isValid(self, s) 23 print(deck) 24 ---> 25 if dict_ab[deck[-1]] == s[i+1]: 26 deck.pop() 27 print(deck) KeyError: ')'

这是一个leetcode问题。 评价为“轻松”。

给定一个仅包含字符 '(', ')', '{', '}', '[' 和 ']' 的字符串,确定输入字符串是否有效。 括号必须以正确的顺序关闭,“()”和“()[]{}”都是有效的,但“(]”和“([)]”不是。

==下面是解决方案所以如果你不想读它,停在这里==

class Solution:
def isValid(self, s):
    """
    :type s: str
    :rtype: bool
    """
    a = ('(','{','[')
    b = (')','}',']')
    dict_ab = dict(zip(a,b))

    import collections

    if (len(s) % 2 == 1) or (len(s) == 0):
        return False
    else:
        deck = collections.deque()
        for i in range(0, len(s), 1):
            if s[i] in a:
                deck.append(s[i])
            else:
                if s[i] in b:
                    if len(deck) == 0:
                        return False
                    else:
                        if s[i] == dict_ab[deck[-1]]:
                            deck.pop()
                        else:
                            return False



        if len(deck) > 0:
            return False

    return True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM