首页 > 编程语言 > 详细

Python中的KMP算法与连续配对KMP算法实现

时间:2021-08-01 18:00:43      阅读:13      评论:0      收藏:0      [点我收藏+]

KMP算法主函数实现:

技术分享图片
def kmp(mom_string, son_string):
    # 传入一个母串和一个子串
    # 返回子串匹配上的第一个位置,若没有匹配上返回-1
    test = ‘‘
    if type(mom_string) != type(test) or type(son_string) != type(test):
        return -1
    if len(son_string) == 0:
        return 0
    if len(mom_string) == 0:
        return -1
    # 求next数组
    next = [-1] * len(son_string)
    if len(son_string) > 1:  # 这里加if是怕列表越界
        next[1] = 0
        i, j = 1, 0
        while i < len(son_string) - 1:  # 这里一定要-1,不然会像例子中出现next[8]会越界的
            if j == -1 or son_string[i] == son_string[j]:
                i += 1
                j += 1
                next[i] = j
            else:
                j = next[j]

    # kmp框架
    m = s = 0  # 母指针和子指针初始化为0
    while (s < len(son_string) and m < len(mom_string)):
        # 匹配成功,或者遍历完母串匹配失败退出
        if s == -1 or mom_string[m] == son_string[s]:
            m += 1
            s += 1
        else:
            s = next[s]

    if s == len(son_string):  # 匹配成功
        return m - s
    # 匹配失败
    return -1
View Code
连续KMP匹配子串位置实现,返回子串位置数组
技术分享图片
def main(str1,str2):
    result = []
    total = 0
    index = kmp(str1, str2)
    pattern_length = len(str2)
    if (index == -1):
        return None
    result.append(index)
    while (index != -1):
        total+=index+2
        str1 = str1[index + pattern_length::]
        index=kmp(str1,str2)
        result.append(total+index)
    result.pop()
    retrun result
View Code

 

Python中的KMP算法与连续配对KMP算法实现

原文:https://www.cnblogs.com/suchcools/p/15086899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!