Created
June 18, 2018 19:26
-
-
Save nch3ng/50d8bccaba08967b19b22472a932be5c to your computer and use it in GitHub Desktop.
Knuth–Morris–Pratt algorithm - get the prefix table
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
# Knuth–Morris–Pratt algorithm - get the prefix table | |
class KMP: | |
def prefixTable(self, s): | |
table = [] | |
table.append(0) | |
j = 0 | |
for i in range(1,len(s)): | |
if s[i] == s[j]: | |
table.append(j+1) | |
j += 1 | |
else: # does not match backward search until match or j = 0 | |
while j != 0: | |
j = table[j-1] | |
if s[j] == s[i]: | |
table.append(j+1) | |
j += 1 | |
break | |
if j == 0: | |
table.append(0) | |
return table | |
print(KMP().prefixTable("ABABACACACABABCA")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment