005_013 Python 寻找子序列 字符串应该用find 否则用KMP

来源:互联网 发布:mac spark 环境搭建 编辑:程序博客网 时间:2024/05/22 04:43

代码如下:

#encoding=utf-8print '中国'#寻找子序列#字符串应该用find 否则用KMPdef KnuthMorrisPratt(text, pattern):        pattern = list(pattern)    length = len(pattern)       shifts = [1] * (length + 1)    shift = 1    for pos, pat in enumerate(pattern):        while shift <= pos and pat != pattern[pos-shift]:            shift += shifts[pos-shift]        shifts[pos+1] = shift        startPos = 0    matchLen = 0    for c in text:        while matchLen == length or matchLen >= 0 and pattern[matchLen] != c:            startPos += shifts[matchLen]            matchLen -= shifts[matchLen]        matchLen += 1        if matchLen == length: yield startPosfor i in KnuthMorrisPratt([1,2,3,4,2,3],[2,3]):    print i

打印结果如下:

中国
1
4


0 0
原创粉丝点击