kmp算法

来源:互联网 发布:网站实时弹幕 源码 编辑:程序博客网 时间:2024/05/16 04:56
#created by sheng.chen at 2015.05.05 def next(str):     retarr = [0] * len(str)     retarr[0] = 0     retarr[1] = 0     for i in range(2,len(str)):         if str[i-1] == str[retarr[i-1]]:             retarr[i] = retarr[i-1] + 1         else:             k = retarr[retarr[i-1]]             while k > 0:                 if str[k] == str[i-1]:                     retarr[i] = k +1                    break                 else:                     k -= 1     return retarr def find(source, target):    nextarr = next(target)                                                                                                                 </span>    i = 0    j = 0     while i < len(source):         if source[i] == target[j]:             i += 1             j += 1         else:             if j == nextarr[j]:                 i += 1             j = nextarr[j]         if j == len(target):             break     if j == len(target):         return i - len(target)     return -1 print find('dsfchencheenchenchenkjh', 'chenchen')
0 0
原创粉丝点击