Skip to content

Instantly share code, notes, and snippets.

@bdss58
bdss58 / lps.py
Last active March 1, 2020 13:29
lsp array for kmp search
def gen_lps(pat):
M = len(pat) # length of pat
current_len_of_lps = 0 # length of the previous longest prefix suffix
lps = [0]*M
if M == 1:
return lps
for i in range(1, M):
if pat[i] == pat[current_len_of_lps]:
current_len_of_lps += 1
lps[i] = current_len_of_lps
@bdss58
bdss58 / kmp.py
Created March 1, 2020 13:30
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