Skip to content

Instantly share code, notes, and snippets.

@nch3ng
Created June 18, 2018 19:26
Show Gist options
  • Save nch3ng/50d8bccaba08967b19b22472a932be5c to your computer and use it in GitHub Desktop.
Save nch3ng/50d8bccaba08967b19b22472a932be5c to your computer and use it in GitHub Desktop.
Knuth–Morris–Pratt algorithm - get the prefix table
# 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