参考博客:http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/
参考博客:http://www.cnblogs.com/c-cloud/p/3224788.html
1.)求nexts数组:
[root@VM_131_54_centos kmp]# python nexts.py
[0, 0, 1, 2, 3, 4]
[0, 0, 1, 2, 3, 4, 0, 1]
[root@VM_131_54_centos kmp]# cat nexts.py
def getNext(s):
nexts=[]
nexts.append(0)
l = len(s)
for x in range(1,l):
d = 0
ss = s[:x+1]
for y in range(0,x):
if ss[:y] == ss[-y:]:
d = y
nexts.append(d)
return nexts
print getNext("bababa")
print getNext("abababca")
下面试下求解匹配到的次数:
[root@VM_131_54_centos kmp]# python n.py
3
1
3
1
0
0:00:00.000122
[root@VM_131_54_centos kmp]# cat n.py
#encoding:utf-8
import datetime
starttime = datetime.datetime.now()
import sys
def getNext(s):
nexts=[]
nexts.append(0)
l = len(s)
for x in range(1,l):
d = 0
ss = s[:x+1]
for y in range(0,x):
if ss[:y] == ss[-y:]:
d = y
nexts.append(d)
return nexts
#子串在父串中出现几次:
#移动步长 = 匹配字符个数 - 最后匹配成功的字符在nexts数组中对应的值
def counts(a,s,n):
la = len(a)
ls = len(s)
j = 0
count = 0
while True:
for i in range(1,ls+1):
if s[i-1] == a[j+i-1]:
if ls ==i:
j += i - n[i-1]
count +=1
else:
j += i - n[i-1]
break
if (la-j) < ls:
break
return count
'''
all = []
t = int(raw_input())
for x in range(0,t):
s = raw_input()
a = raw_input()
all.append([s,a])
for x in range(0,t):
n = getNext(all[x][0])
print counts(all[x][1],all[x][0],n)
'''
s = "HA"
a = 'HAHAHA'
n = getNext(s)
print counts(a,s,n)
s = "WQN"
a = 'WQN'
n = getNext(s)
print counts(a,s,n)
s = "ADA"
a = 'ADADADA'
n = getNext(s)
print counts(a,s,n)
s = "BABABB"
a = 'BABABABABABABABABB'
n = getNext(s)
print counts(a,s,n)
s = "DAD"
a = 'ADDAADAADDAAADAAD'
n = getNext(s)
print counts(a,s,n)
endtime = datetime.datetime.now()
print (endtime-starttime)
但是 改为获取用户输入时,TLE了。再改。不知道哪里出问题了。