-
Notifications
You must be signed in to change notification settings - Fork 88
/
KMP.py
65 lines (57 loc) · 1.35 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
54
55
56
57
58
59
60
61
62
63
64
65
#coding: utf-8
''' mbinary
#########################################################################
# File : KMP.py
# Author: mbinary
# Mail: [email protected]
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-12-11 14:02
# Description:
#########################################################################
'''
def getPrefixFunc(s):
'''return the list of prefix function of s'''
length = 0
i = 1
n = len(s)
ret = [0]
while i < n:
if s[i] == s[length]:
length += 1
ret.append(length)
i += 1
else:
if length == 0:
ret.append(0)
i += 1
else:
length = ret[length-1]
return ret
def findAll(s, p):
pre = getPrefixFunc(p)
i = j = 0
n, m = len(s), len(p)
ret = []
while i < n:
if s[i] == p[j]:
i += 1
j += 1
if j == m:
ret.append(i-j)
j = pre[j-1]
else:
if j == 0:
i += 1
else:
j = pre[j-1]
return ret
def randStr(n=3):
return [randint(ord('a'), ord('z')) for i in range(n)]
if __name__ == '__main__':
from random import randint
s = randStr(50)
p = randStr(1)
print(s)
print(p)
print(findAll(s, p))