You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Original Code: https://github.com/MISabic/dsa-implementation/blob/main/string%20matching/KMP/KMP.py
2
+
3
+
defkmp_table(pattern):
4
+
# Create a table to store the values of the longest proper prefix that is also a suffix of the substring for each position in the pattern.
5
+
table= [0] *len(pattern)
6
+
7
+
# Initialize the left and right pointers to zero and one, respectively.
8
+
left, right=0, 1
9
+
10
+
# Iterate over the pattern from left to right
11
+
whileright<len(pattern):
12
+
# If the character at the right pointer is equal to the character at the left pointer, increment both pointers and set the value of the table at the right pointer to the value of the left pointer.
13
+
ifpattern[right] ==pattern[left]:
14
+
left+=1
15
+
table[right] =left
16
+
right+=1
17
+
18
+
else:
19
+
# If the characters are not equal, move the left pointer back to the position in the table corresponding to the previous longest proper prefix that is also a suffix, and continue checking for a match.
20
+
ifleft!=0:
21
+
left=table[left-1]
22
+
23
+
else:
24
+
# If there is no previous longest proper prefix that is also a suffix, set the value of the tabe at the right pointer to zero and move pointer forward.
25
+
table[right] =0
26
+
right+=1
27
+
28
+
29
+
returntable
30
+
31
+
32
+
33
+
defkmp_search(text, pattern):
34
+
# Create a table to store the values of the longest proper prefix that is also a suffix of the substring for each position in the pattern.
35
+
table=kmp_table(pattern)
36
+
37
+
# Initialize variables for the indicies of the text and pattern.
38
+
i, j=0, 0
39
+
40
+
# Iterate over the text while the index is less than the length of the text.
41
+
whilei<len(text):
42
+
# If the characters at the current indicies match, increment both indicies.
43
+
iftext[i] ==pattern[j]:
44
+
i+=1
45
+
j+=1
46
+
47
+
# If the value of j is equal to the length of the pattern, the pattern has been found in the text, so return the index where it starts.
48
+
ifj==len(pattern):
49
+
returni-j
50
+
51
+
else:
52
+
# If the characters do not match and j is not zero, move the j index to the value in the table corresponding to the previous longest proper prefix that is also a suffix, and continue checking for a match.
53
+
ifj!=0:
54
+
j=table[j-1]
55
+
else:
56
+
# If there is no previous longest proper prefix that is also a suffix, move the i index forward.
0 commit comments