2018-12-11 15:28:05 +08:00
|
|
|
#coding: utf-8
|
|
|
|
''' mbinary
|
|
|
|
#########################################################################
|
|
|
|
# File : KMP.py
|
|
|
|
# Author: mbinary
|
|
|
|
# Mail: zhuheqin1@gmail.com
|
2019-01-31 12:09:46 +08:00
|
|
|
# Blog: https://mbinary.xyz
|
2018-12-11 15:28:05 +08:00
|
|
|
# Github: https://github.com/mbinary
|
|
|
|
# Created Time: 2018-12-11 14:02
|
|
|
|
# Description:
|
|
|
|
#########################################################################
|
|
|
|
'''
|
|
|
|
|
2020-04-15 12:28:20 +08:00
|
|
|
|
2018-12-11 15:28:05 +08:00
|
|
|
def getPrefixFunc(s):
|
|
|
|
'''return the list of prefix function of s'''
|
|
|
|
length = 0
|
|
|
|
i = 1
|
|
|
|
n = len(s)
|
|
|
|
ret = [0]
|
2020-04-15 12:28:20 +08:00
|
|
|
while i < n:
|
|
|
|
if s[i] == s[length]:
|
|
|
|
length += 1
|
2018-12-11 15:28:05 +08:00
|
|
|
ret.append(length)
|
2020-04-15 12:28:20 +08:00
|
|
|
i += 1
|
2018-12-11 15:28:05 +08:00
|
|
|
else:
|
2020-04-15 12:28:20 +08:00
|
|
|
if length == 0:
|
2018-12-11 15:28:05 +08:00
|
|
|
ret.append(0)
|
2020-04-15 12:28:20 +08:00
|
|
|
i += 1
|
2018-12-11 15:28:05 +08:00
|
|
|
else:
|
|
|
|
length = ret[length-1]
|
|
|
|
return ret
|
|
|
|
|
2020-04-15 12:28:20 +08:00
|
|
|
|
|
|
|
def findAll(s, p):
|
2018-12-11 15:28:05 +08:00
|
|
|
pre = getPrefixFunc(p)
|
2020-04-15 12:28:20 +08:00
|
|
|
i = j = 0
|
|
|
|
n, m = len(s), len(p)
|
2018-12-11 15:28:05 +08:00
|
|
|
ret = []
|
2020-04-15 12:28:20 +08:00
|
|
|
while i < n:
|
|
|
|
if s[i] == p[j]:
|
|
|
|
i += 1
|
|
|
|
j += 1
|
|
|
|
if j == m:
|
2018-12-11 15:28:05 +08:00
|
|
|
ret.append(i-j)
|
2020-04-15 12:28:20 +08:00
|
|
|
j = pre[j-1]
|
2018-12-11 15:28:05 +08:00
|
|
|
else:
|
2020-04-15 12:28:20 +08:00
|
|
|
if j == 0:
|
|
|
|
i += 1
|
|
|
|
else:
|
|
|
|
j = pre[j-1]
|
2018-12-11 15:28:05 +08:00
|
|
|
return ret
|
2020-04-15 12:28:20 +08:00
|
|
|
|
|
|
|
|
2018-12-11 15:28:05 +08:00
|
|
|
def randStr(n=3):
|
2020-04-15 12:28:20 +08:00
|
|
|
return [randint(ord('a'), ord('z')) for i in range(n)]
|
|
|
|
|
2018-12-11 15:28:05 +08:00
|
|
|
|
2020-04-15 12:28:20 +08:00
|
|
|
if __name__ == '__main__':
|
2018-12-11 15:28:05 +08:00
|
|
|
from random import randint
|
|
|
|
s = randStr(50)
|
|
|
|
p = randStr(1)
|
|
|
|
print(s)
|
|
|
|
print(p)
|
2020-04-15 12:28:20 +08:00
|
|
|
print(findAll(s, p))
|