算法原理:http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
next数组还不是太理解,代码如下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time : 2017/12/5 下午8:19
# @desc :
def get_next(p):
next = [0] * len(p)
next[0] = -1
i = 0
k = -1
while i < len(p)-1:
if k == -1 or p[i] == p[k]:
i += 1
k += 1
next[i] = k
else:
k = next[k]
return next
def kmp(s, p):
if len(p) == 0:
return 0
next = get_next(p)
i, j = 0, 0
while i < len(s) and j < len(p):
if j == -1 or s[i] == p[j]:
i += 1
j += 1
else:
j = next[j]
if j == len(p):
return i - len(p)
else:
return -1
if __name__ == "__main__":
next = get_next("abcbabca")
res = kmp("abcdabcdabcde", "abcde")
print res