python KMP算法

KMP算法

KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt提出的,因此人们称它为克努特—莫里斯—普拉特操作(简称KMP算法)。KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是通过一个next数组来实现,函数本身包含了模式串的局部匹配信息。KMP算法的时间复杂度O(m+n)。

python代码实现

# str1  和 str2
def KMP_index(str1, str2):
    i1, i2 = 0, 0
    next_list = GetNextArray(str2)
    while i1 < len(str1) and i2 < len(str2):
        if str1[i1] == str2[i2]:
            i1 += 1
            i2 += 1
        elif next_list[i2] == -1:
            i1 += 1
        else:
            i2 = next_list[i2]
    return i1 - i2 if i2 == len(str2) else -1


def GetNextArray(str2):
    """
    构建netx_list数组
    :param str2:
    :return:
    """
    if len(str2) == 1:
        return -1
    next_list = [-1] * len(str2)
    next_list[0], next_list[1] = -1, 0
    i, cn = 2, 0
    while i < len(str2):
        if str2[i - 1] == str2[cn]:
            cn += 1
            next_list[i] = cn
            i += 1
        elif cn > 0:
            cn = next_list[cn]
        else:
            next_list[i] = 0
            i += 1

    return next_list


if __name__ == '__main__':
    string1 = "adsfdasfsdf"
    string2 = "asf"
    a = KMP_index(string1,string2)
    print(a)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
KMP算法是一种字符串匹配算法,用于查找一个字符串(模式串)在另一个字符串(文本串)中的出现位置。它的时间复杂度为O(m+n),其中m和n分别是模式串和文本串的长度。 KMP算法的核心思想是利用已经匹配过的部分来跳过一些无需匹配的部分,从而提高匹配效率。具体实现如下: 1. 预处理模式串,生成next数组。next[i]表示模式串前i个字符组成的子串中,最长的相等前缀后缀的长度。例如,模式串"ABCDABD"的next数组为[-1,0,0,0,0,1,2,0]。 2. 在文本串中匹配模式串。从文本串的第一个字符开始,依次和模式串进行匹配。如果匹配成功,继续匹配下一个字符;如果匹配失败,则根据next数组跳过一些无需匹配的部分。 代码实现如下: ```python def kmp(text, pattern): n, m = len(text), len(pattern) if m == 0: return 0 # 生成next数组 next = [0] * m j = 0 for i in range(1, m): while j > 0 and pattern[i] != pattern[j]: j = next[j-1] if pattern[i] == pattern[j]: j += 1 next[i] = j # 在文本串中匹配模式串 j = 0 for i in range(n): while j > 0 and text[i] != pattern[j]: j = next[j-1] if text[i] == pattern[j]: j += 1 if j == m: return i - m + 1 return -1 ``` 其中,next数组的生成过程采用了类似动态规划的思想,通过已经匹配过的部分来推导下一步的匹配位置。在匹配过程中,如果当前字符匹配失败,则根据next数组跳过一些无需匹配的部分,以提高匹配效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值