-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkmp_algo.py
56 lines (42 loc) · 890 Bytes
/
kmp_algo.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
__author__ = "Shashwat Tiwari"
__email__ = "shashwat1791@gmail.com"
class KMPAlgorithm:
def __init__(self):
pass
def search(self, text, pattern):
i = 0
j = 0
lps = self.calculateLPS(pattern)
while i < len(text):
if text[i] == pattern[j]:
i += 1
j += 1
if j == len(pattern):
print "Pattern Found at index: {}".format(i-j)
j = lps[j-1]
elif i < len(text) and text[i] != pattern[j]:
if j != 0:
j = lps[j-1]
else:
i += 1
def calculateLPS(self, pattern):
j = 0
i = 1
lps = [0]*len(pattern)
lps[0] = 0
while i < len(pattern):
if pattern[i] == pattern[j]:
j += 1
lps[i] = j
i += 1
else:
if j != 0:
j = lps[j-1]
else:
lps[i] = j
i += 1
return lps
if __name__ == "__main__":
text = "sssxsss"
pattern = "sss"
KMPAlgorithm().search(text, pattern)