Skip to content

Commit

Permalink
Merge pull request #361 from abdulwd/issue#347
Browse files Browse the repository at this point in the history
Add KMP search algorithm in python.
  • Loading branch information
BaReinhard authored Oct 31, 2017
2 parents 11e9854 + 08ad250 commit b747ec2
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions algorithms/kmp_search/python/KMPSearch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class KMP:
def partial(self, pattern):
""" Calculate partial match table: String -> [Int]"""
ret = [0]

for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
ret.append(j + 1 if pattern[j] == pattern[i] else j)
return ret

def search(self, T, P):
"""
KMP search main algorithm: String -> String -> [Int]
Return all the matching position of pattern string P in S
"""
partial, ret, j = self.partial(P), [], 0

for i in range(len(T)):
while j > 0 and T[i] != P[j]:
j = partial[j - 1]
if T[i] == P[j]: j += 1
if j == len(P):
ret.append(i - (j - 1))
j = 0

return ret

0 comments on commit b747ec2

Please sign in to comment.