KMP字符串匹配算法

# -*- coding: utf-8 -*-
"""
Created on 2020-04-02 16:01:54

简介:KMP字符串匹配

@author: 杨h  [email protected] 
"""

def gen_pnext(substr):
    m = len(substr)
    pnext = [0]*m
    j = 0
    i = 1
    while i < m:
        if substr[j] == substr[i]:
            pnext[i] = j+1
            j += 1
            i += 1
        elif j != 0:
            j = pnext[j-1]
        else:
            pnext[i] = 0
            i += 1
    return pnext

gen_pnext('abcabgac')
# [out]:[0, 0, 0, 1, 2, 0, 1, 0]
def KMP_algh(string, substring):
    pnext = gen_pnext(substring)
    i, j = 0, 0
    n = len(string)
    m = len(substring)
    while j

参考文章

你可能感兴趣的:(KMP字符串匹配算法)