defkmp_string_search(s, p): """ :param s:string :param p:string, pattern :return:list """ # build pattern string array m = len(p) li = [0] * (m+1) i = 0 for j in range(1, m): while i > 0and p[j] != p[i]: i = li[i]
# 当有j+1个字符的时候,有i+1个前后缀重叠 if p[j] == p[i]: i += 1 li[j+1] = i + 1
# use above array to search n = len(s) i = 0 finds = [] for j in range(0, n): while i > 0and s[j] != p[i]: i = li[i] if s[j] == p[i]: if i == m-1: finds.append(j-m+1) i = li[i+1] else: i += 1 return finds
if __name__ == "__main__": s = 'bacbababaabcbababacababacababacababacb' p = 'ababacab' print(s) print(p) finds = kmp_string_search(s, p) for index in finds: print('-'*len(s)) print(s) print('%s%s' % (' '*index, p))