Skip to content

Instantly share code, notes, and snippets.

@bdss58
Created March 1, 2020 13:30
Show Gist options
  • Save bdss58/f89ddfaf72384b5c4823c2c018686840 to your computer and use it in GitHub Desktop.
Save bdss58/f89ddfaf72384b5c4823c2c018686840 to your computer and use it in GitHub Desktop.
KMP pattern search algorithm
from lps import gen_lps # reference lps.py
def kmp_search(pat, txt):
N = len(txt)
M = len(pat)
lps = gen_lps(pat)
print('here', lps)
i, j = 0, 0
while i < N:
if pat[j] == txt[i]:
j += 1
i += 1
if j == M:
print(f'found at {i-M}')
j = lps[j-1]
if i < N and pat[j] != txt[i]:
if j != 0:
j = lps[j-1]
else:
i += 1
if __name__ == "__main__":
txt = "ABABDABACDABABCABABddddddddABABCABABddABABCABAB"
pat = "ABABCABAB"
kmp_search(pat, txt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment