KMP算法数组越界力扣28题

问题遇到的现象和发生背景

list assignment index out of range

问题相关代码,请勿粘贴截图
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:

        def getNext(a,needle):
            next = ['' for _ in range(a)]
            k = -1
            next[0] = k       #list assignment index out of range
            for i in range(1, a):
                while k > -1 and needle[k+1] != haystack[i]:
                    k = next[k]
                if needle[k+1] == haystack[i]:
                    k += 1
                next[i] = k
            return next
        

        a = len(needle)    #模式串
        b = len(haystack)  #母串
        p = -1
        next = getNext(a, needle)
        if a == 0:
            return 0
        for j in range(b):
            while p >= 0 and needle[p+1] != haystack[j]:
                p = next[p]
            if needle[p+1] == haystack[j]:
                p += 1
            if p == a - 1:
                return j - a + 1
        return -1

运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果