-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP_StringMatching.py
More file actions
39 lines (33 loc) · 1.14 KB
/
Copy pathKMP_StringMatching.py
File metadata and controls
39 lines (33 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# String Matching Krusk’s Moris Pratt Algo:
def kmp_string_matching(needle, heystack):
if not needle: return 0
lps = [0 for _ in needle]
prevLps = 0 # previous prefix setter and pointer to prev char in needle
i = 1 # current char/symbol pointer
while i < len(needle): # building Longest Prefix Suffix array/ ds
if needle[i] == needle[prevLps]: # if prefix is found to the left of the current char/symbol
lps[i] = prevLps + 1
i += 1
prevLps += 1
elif prevLps == 0: # if no prefix is found at all
lps[i] = 0
i += 1
else: # if not yet find prifix
prevLps = lps[prevLps - 1]
i = 0 # haystack pointer
j = 0 # needle pointer
while i < len(heystack):
if needle[j] == heystack[i]:
i, j = i + 1, j + 1
else:
if j == 0:
i += 1
else:
j = lps[j - 1]
if j == len(needle):
match_index = i - len(needle)
return match_index
return -1
needle = 'hey'
heystack = 'heystack'
print(kmp_string_matching(needle, heystack))