Skip to content

Commit 62b31b2

Browse files
Create kmpalgo.py
1 parent eeb2499 commit 62b31b2

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

DSA/kmpalgo.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Python program for KMP Algorithm
2+
def KMPSearch(pat, txt):
3+
M = len(pat)
4+
N = len(txt)
5+
6+
# create lps[] that will hold the longest prefix suffix
7+
# values for pattern
8+
lps = [0]*M
9+
j = 0 # index for pat[]
10+
11+
# Preprocess the pattern (calculate lps[] array)
12+
computeLPSArray(pat, M, lps)
13+
14+
i = 0 # index for txt[]
15+
while i < N:
16+
if pat[j] == txt[i]:
17+
i += 1
18+
j += 1
19+
20+
if j == M:
21+
print ("Found pattern at index", str(i-j))
22+
j = lps[j-1]
23+
24+
# mismatch after j matches
25+
elif i < N and pat[j] != txt[i]:
26+
# Do not match lps[0..lps[j-1]] characters,
27+
# they will match anyway
28+
if j != 0:
29+
j = lps[j-1]
30+
else:
31+
i += 1
32+
33+
def computeLPSArray(pat, M, lps):
34+
len = 0 # length of the previous longest prefix suffix
35+
36+
lps[0] # lps[0] is always 0
37+
i = 1
38+
39+
# the loop calculates lps[i] for i = 1 to M-1
40+
while i < M:
41+
if pat[i]== pat[len]:
42+
len += 1
43+
lps[i] = len
44+
i += 1
45+
else:
46+
# This is tricky. Consider the example.
47+
# AAACAAAA and i = 7. The idea is similar
48+
# to search step.
49+
if len != 0:
50+
len = lps[len-1]
51+
52+
# Also, note that we do not increment i here
53+
else:
54+
lps[i] = 0
55+
i += 1
56+
57+
txt = "ABABDABACDABABCABAB"
58+
pat = "ABABCABAB"
59+
KMPSearch(pat, txt)

0 commit comments

Comments
 (0)