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