i + = 2不能在这个python代码中工作

时间:2017-12-06 18:43:59

标签: python-3.x

我正在学习如何编码,会欣赏任何输入。这是我为解决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()
        #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: ')'

问题在于,当第一次dict_ab [deck [-1]] == s [i + 1]时,在执行deck.pop()之后,它然后迭代i到i + = 2。然而,这没有发生,我自动只+ + 1。我做错了什么?我一直在研究这一天,无法解决这个问题。任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个leetcode问题。评为&#34; Easy&#34;。

如果字符串只包含字符&#39;(&#39;,&#39;)&#39;,&#39; {&#39;,&#39;}&#39;, &#39; [&#39;和&#39;]&#39;,确定输入字符串是否有效。 括号必须以正确的顺序关闭,&#34;()&#34;和&#34;()[] {}&#34;都是有效的,但&#34;(]&#34;和&#34;([)]&#34;不是。

==以下是解决方案,如果您不想阅读,请在此处停止==

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