Created
March 1, 2020 13:30
-
-
Save bdss58/f89ddfaf72384b5c4823c2c018686840 to your computer and use it in GitHub Desktop.
KMP pattern search algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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