KMP初试
2017-10-31 20:46
246 查看
参考博客: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数组:
下面试下求解匹配到的次数:
但是 改为获取用户输入时,TLE了。再改。不知道哪里出问题了。
参考博客: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了。再改。不知道哪里出问题了。
相关文章推荐
- 初试KMP!
- poj 3461 Oulipo (KMP)
- POJ 2406 KMP 循环节
- 初试.bat文件运行java程序
- jquery-mockjax初试
- kmp
- 【经典算法】——KMP,深入讲解next数组的求解
- poj 3461 Oulipo(KMP)
- HDU 3336 Count the string(KMP)
- KMP字符排序
- 判断s各个前缀是否是 ABABA…ABA的形式 KMP Codeforces 526D - Om Nom and Necklace
- KMP算法基本思想与实现
- HDU - 1711 Number Sequence(KMP)
- kmp poj 3450 3461
- hdu(kmp的应用)
- flash cs6 初试
- HUST 1010 The Minimum Length(kmp求周期)
- hdu 1686(kmp)
- hust 1010 The Minimum Length(KMP求最小循环节)
- KMP