-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP-string.py
40 lines (31 loc) · 881 Bytes
/
KMP-string.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
# Algorithm to illustrate KMP algorithm
class Solution:
def getPiTable(self,s):
# Initialize pi table
pi=[0]*(len(s)+1)
pi[0]=-1
# Initialize K
k=-1
s=list(s)
s.insert(0,'-1')
for i in range(1,len(s)):
while(k>=0 and s[k+1]!=s[i]):
k=pi[k]
k=k+1
pi[i]=k
print(pi)
return pi
def doesPatternExist(self,s,p):
pi=self.getPiTable(p)
p='1'+p
k=0
for i in range(len(s)):
c=s[i]
while(k>=0 and p[k+1]!=c):
k=pi[k]
k=k+1
if(k==len(p)-1):
return i-len(p)-1
return -1
s=Solution()
print(s.doesPatternExist('abc abcdab abcdabcdabde','abcdabd'))