KMP算法

作者: 何大炮 | 来源:发表于2018-05-10 12:12 被阅读0次

看毛片算法的具体细节:详解
主字符为:m, 查找字符为:n
该算法用于字符匹配,时间复杂度为O(m+n),空间复杂度为:O(n)
我这里准备实现一个python3版的代码。
考虑到对于next的实现有些复杂,这里附上讲解

# KMP
def next_kmp(nums):
    next_list = [-1]
    i = 0
    j = next_list[0]
    while i < len(nums)-1:
        if j == -1 or nums[i] == nums[j]:
            i += 1
            j += 1
            next_list.append(j)
        else:
            j = next_list[j]
    return next_list

def kmp(long_str, short_str):
    next_list = next_kmp(short_str)
    start = 0
    short_location = 0
    while start < len(long_str):
        if long_str[start] == short_str[short_location] or short_location == -1:
            start += 1
            short_location += 1

            if short_location == len(short_str):
                return start - short_location
        else:
            short_location = next_list[short_location]

    return False

test = "abcabcabdabab"
lo = kmp(test, 'abab')
print(lo)

相关文章

  • KMP 专题整理

    KMP 学习记录 kuangbin专题十六——KMP KMP 学习总结 朴素 KMP 算法 拓展 KMP 算法(E...

  • 对KMP算法的一些理解

    最近学到KMP算法,下面讲讲对KMP算法的一些个人理解,希望对大家有帮助! 对于KMP算法的理解: 整个KMP算法...

  • KMP算法文章合集

    字符串的查找:朴素查找算法和KMP算法 暴力匹配算法与KMP算法(串的匹配) 字符串查找算法BF和KMP 字符串匹...

  • 串的模式匹配算法

    KMP算法 算法匹配

  • 问答|KMP算法学习笔记

    问题 目录KMP是什么,做什么用的KMP算法的高效体现在哪如何KMP算法的next数组KMP的代码KMP的时间复杂...

  • KMP算法——寻找子串位置

    KMP算法——寻找子串位置 1、KMP算法简介: KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J....

  • 字符串匹配 - KMP算法

    前面我们介绍非常高效的 BM 算法,今天我们介绍另一个非常出名且高效的 KMP 算法。 KMP 算法思想 KMP ...

  • KMP算法及优化

    转载请注明出处: KMP算法及优化 今天看到同学在复习数据结构书上的KMP算法,忽然发觉自己又把KMP算法忘掉了,...

  • KMP算法(字符串匹配问题)

    一、是什么? 注意,是KMP算法,不是MMP哈,我没有骂人。KMP算法是用来做字符串匹配的,除了KMP算法分,还有...

  • KMP算法

    KMP算法

网友评论

      本文标题:KMP算法

      本文链接:https://www.haomeiwen.com/subject/hxtcrftx.html