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

请问为什么我的列表下标明明能找到数据还会提示我列表下标越界?(输入的字符串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在函数中打印信息分析问题

外层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里

a += 1
这是要干嘛
你的for循环a每次都会自动增加1
按照你的思路,就不要用for循环
而是

while a < n:
    ...