Algoritmo
def match(S, w):
result = []
for i in 1..len(S):
for j in 1..len(w):
if S[i + j - 1] != w[j]:
break
else:
result.append(i)
return result
Algoritmo
def pre_KMP(w):
kmp_next = [-1] * len(w)
i = 0
j = kmp_next[0]
while i < len(w):
while j > -1 and w[i] != w[j]:
j = kmp_next[j]
i += 1
j += 1
if w[i] == w[j]:
kmp_next[i] = kmp_next[j]
else:
kmp_next[i] = j
return kmp_next
def match(S, w):
result = []
kmp_next = pre_KMP(w)
i = j = 0
while j < len(S):
while i > -1 and w[i] != S[j]:
i = kmp_next[i]
i += 1
j += 1
if i >= len(w):
result.append(j - i)
i = kmp_next[i]
return result