forked from The-Open-Source-Society/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
KMP.py
53 lines (42 loc) · 1.02 KB
/
KMP.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
def calculateLps(pattern, lps):
length = 0
lps[0] = 0
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
def KMPSearch(pattern, text):
sizePattern = len(pattern)
sizeText = len(text)
lps = [0] * sizePattern
j = 0
calculateLps(pattern, lps)
i = 0
while i < sizeText:
if pattern[j] == text[i]:
i+=1
j+=1
if j == sizePattern:
print("Pattern found at " + str(i - j + 1))
j = lps[j - 1]
elif i < sizeText and pattern[j] != text[i]:
if j != 0:
j = lps[j - 1]
else:
i += 1
text = "namanchamanbomanamansanam"
pattern = "aman"
KMPSearch(pattern, text)
''' Output
Pattern found at 2
Pattern found at 8
Pattern found at 17
'''