Python KMP算法

KMP算法(Knuth-Morris-Pratt算法)是一种用于在字符串中查找子字符串的高效算法,它利用了已匹配的部分信息来避免不必要的回溯。下面是一个示例代码,展示如何使用Python实现KMP算法:

cpp 复制代码
def compute_lps(pattern):
    lps = [0] * len(pattern)
    j = 0
    i = 1
    while i < len(pattern):
        if pattern[i] == pattern[j]:
            j += 1
            lps[i] = j
            i += 1
        else:
            if j != 0:
                j = lps[j - 1]
            else:
                lps[i] = 0
                i += 1
    return lps

def kmp_search(text, pattern):
    lps = compute_lps(pattern)
    i = 0
    j = 0
    while i < len(text):
        if text[i] == pattern[j]:
            i += 1
            j += 1
        if j == len(pattern):
            print("Pattern found at index", i - j)
            j = lps[j - 1]
        elif i < len(text) and text[i] != pattern[j]:
            if j != 0:
                j = lps[j - 1]
            else:
                i += 1

# 测试示例
text = "ABABDABACDABABCABAB"
pattern = "ABABCABAB"
kmp_search(text, pattern)

在上面的示例中,compute_lps函数用于计算给定模式字符串的最长公共前缀和后缀的长度(LPS数组),而kmp_search函数则利用LPS数组来实现KMP算法的字符串匹配。在测试示例中,我们在文本字符串中搜索模式字符串,并打印出匹配的索引位置。

KMP算法的关键在于构建LPS数组,该数组可以帮助我们在匹配过程中跳过一些不必要的比较。这样可以提高字符串匹配的效率。

相关推荐
爱编程的鱼8 小时前
OpenCV Python 绑定:原理与实战
c语言·开发语言·c++·python
这周也會开心8 小时前
云服务器安装JDK、Tomcat、MySQL
java·服务器·tomcat
hrrrrb9 小时前
【Spring Security】Spring Security 概念
java·数据库·spring
小信丶9 小时前
Spring 中解决 “Could not autowire. There is more than one bean of type“ 错误
java·spring
周杰伦_Jay10 小时前
【Java虚拟机(JVM)全面解析】从原理到面试实战、JVM故障处理、类加载、内存区域、垃圾回收
java·jvm
晓风残月淡10 小时前
JVM字节码与类的加载(二):类加载器
jvm·python·php
西柚小萌新12 小时前
【深入浅出PyTorch】--上采样+下采样
人工智能·pytorch·python
未来之窗软件服务13 小时前
自己写算法(九)网页数字动画函数——东方仙盟化神期
前端·javascript·算法·仙盟创梦ide·东方仙盟·东方仙盟算法
程序员小凯13 小时前
Spring Boot测试框架详解
java·spring boot·后端
豐儀麟阁贵13 小时前
基本数据类型
java·算法