Python Template for KMP Algorithm:
# Build the prefix table (next array)
j = 0
for i in range(2, n + 1):
while j and p[i] != p[j + 1]:
j = ne[j]
if p[i] == p[j + 1]:
j += 1
ne[i] = j
# KMP matching
j = 0
for i in range(1, m + 1):
while j and s[i] != p[j + 1]:
j = ne[j]
if s[i] == p[j + 1]:
j += 1
if j == n:
# find matching
Key Points:
- Pad to make Pattern and Source all 1-indexed
- Createt the next(prefix) table