KMP初试

参考博客: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了。再改。不知道哪里出问题了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值