-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkmp.py
39 lines (33 loc) · 792 Bytes
/
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
haystack = 'asdabcabdjabcdabcdababcgj'
needle = 'abcdababc'
p = [0] * len(needle)
p[0] = 0
# len(needle) should be > 0 otherwise answer is 0 (like in java impl)
j, i = 0, 1
while i < len(needle):
if needle[j] == needle[i]:
p[i] = j + 1
i += 1
j += 1
else:
if j == 0:
p[i] = 0
i += 1
else:
j = p[j - 1]
print(f'{p=}')
i = j = 0
while i < len(haystack):
if haystack[i] == needle[j]:
i += 1
j += 1
if j == len(needle):
print('Substring starts from', i - j, haystack[i - j:i - j + len(needle)])
break
else:
if j > 0:
j = p[j - 1]
else:
i += 1
if i == len(haystack):
print('Haystack doesnt contain needle')