KMP Failure Function Pattern Match (Python)
Match a pattern in text using KMP with a precomputed failure function for linear time matching.
Code
def kmp_search(text, pattern):
n, m = len(text), len(pattern)
if m == 0:
return [0]
fail = [0] * m
j = 0
for i in range(1, m):
while j > 0 and pattern[i] != pattern[j]:
j = fail[j - 1]
if pattern[i] == pattern[j]:
j += 1
fail[i] = j
result = []
j = 0
for i in range(n):
while j > 0 and text[i] != pattern[j]:
j = fail[j - 1]
if text[i] == pattern[j]:
j += 1
if j == m:
result.append(i - m + 1)
j = fail[j - 1]
return resultReport a problem with this exampleOpens a pre-filled issue on GitHub.