qq_46390056 2023-07-05 00:24 采纳率: 100%
浏览 55
已结题

为什么列表下标明明没有越界却还会报错?

请问为什么我的列表下标明明能找到数据还会提示我列表下标越界?(输入的字符串s为"[]")

class Solution:
    def isValid(self , s: str) -> bool:
        # write code here
        n = len(s)
        if n%2 != 0:
            return False
        ls = []
        for a in range(n):
            while a<n and (s[a] == '(' or s[a] == '[' or s[a] == '{'):
                ls.append(s[a])
                a += 1
            if s[a] == ')' and ls[-1] == '(':
                ls.pop()
            elif s[a] == ']' and ls[-1] == '[':
                ls.pop()
            elif s[a] == '}' and ls[-1] == '{':
                ls.pop()
        if not ls:
            return True
        else :
            return False
程序异常退出, 请检查代码"是否有数组越界等异常"或者"是否有语法错误"
File "/tmp/a.py3", line 16, in run
ret = solution.isValid( s )
File "/tmp/solution.py", line 21, in isValid
elif s[a] == ']' and ls[-1] == '[':
IndexError: list index out of range
您可以用print在函数中打印信息分析问题
  • 写回答

2条回答 默认 最新

  • 於黾 2023-07-05 07:40
    关注

    外层for循环,内层while循环,并不能很好的对a的取值进行控制,导致bug
    改成这样

    def isValid(self ,s: str) -> bool:
        # write code here
        n = len(s)
        if n % 2 != 0:
            return False
        ls = []
        a = 0
        while a < n:
            while a < n and (s[a] == '(' or s[a] == '[' or s[a] == '{'):
                ls.append(s[a])
                a += 1
            if a < n and s[a] == ')' and ls[-1] == '(':
                ls.pop()
            elif a < n and s[a] == ']' and ls[-1] == '[':
                ls.pop()
            elif a < n and s[a] == '}' and ls[-1] == '{':
                ls.pop()
            a += 1
        if not ls:
            return True
        else:
            return False
    

    问题的关键在于,内层已经将a遍历到3了,回到外层,a又变回1,会反复将同一个符号塞进list里

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月13日
  • 已采纳回答 7月5日
  • 修改了问题 7月5日
  • 创建了问题 7月5日