forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* [ADD] Added KMP algorithm. * [ADD] Added test case for KMP algorithm * [EDIT] Imported KMP algorithm * [EDIT] Added KMP algorithm in README * [EDIT] Added test case for KMP algorithm * [EDIT] Edited description of algorithm with more detail * [FIX] Fixed minor bug * [EDIT] Added test case for edge cases
- Loading branch information
Showing
4 changed files
with
51 additions
and
1 deletion.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
""" | ||
Given two strings text and pattern, | ||
return the list of start indexes in text that matches with the pattern | ||
using knuth_morris_pratt algorithm. | ||
If idx is in the list, text[idx : idx + M] matches with pattern. | ||
Time complexity : O(N+M) | ||
N and M is the length of text and pattern, respectively. | ||
""" | ||
|
||
def knuth_morris_pratt(text, pattern): | ||
n = len(text) | ||
m = len(pattern) | ||
pi = [0 for i in range(m)] | ||
i = 0 | ||
j = 0 | ||
# making pi table | ||
for i in range(1, m): | ||
while j and pattern[i] != pattern[j]: | ||
j = pi[j - 1] | ||
if pattern[i] == pattern[j]: | ||
j += 1 | ||
pi[i] = j | ||
# finding pattern | ||
j = 0 | ||
ret = [] | ||
for i in range(n): | ||
while j and text[i] != pattern[j]: | ||
j = pi[j - 1] | ||
if text[i] == pattern[j]: | ||
j += 1 | ||
if j == m: | ||
ret.append(i - m + 1) | ||
j = pi[j - 1] | ||
return ret |
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