美文网首页
【算法】KMP

【算法】KMP

作者: 如雨随行2020 | 来源:发表于2024-03-27 01:18 被阅读0次

[toc]

一、KMP算法说明

要判断s1字符串是否包含s2字符串,如果包含返回s1中包含s2的最左开头位置,不包含返回-1

暴力方法就是s1的每个位置都做开头,然后去匹配s2整体,时间复杂度O(n*m),其中n为s1长度,m为s2长度

KMP算法可以做到时间复杂度O(n+m)

二、详细实现

1. next数组定义

字符串s的next数组为int数组,长度等于s的长度。next[i]表示在s中下标i之前子串的<font color="red">前缀和后缀的最大匹配长度</font>(不包含整体)

以字符串"aabaabs"为例

// i=0,规定next[0]为-1
// i=1,由于s[1]之前只有a,除去整体,前缀和后缀只能是空,所以规定next[1]=0
// i=2, "aa",前缀"a",后缀"a",最大匹配长度1,next[2]=1
// i=3, "aab",没有可以匹配的前缀和后缀,next[3]=0
// i=4, "aaba", 前缀"a", 后缀"a", next[4]=1
// i=5, "aabaa", 前缀"aa", 后缀"aa", next[5]=2
// i=6, "aabaab", 前缀"aab", 后缀"aab", next[6]=3
// 扩充的next是可以多计算一位的
// i=7, "aabaabs",没有可以匹配的前缀和后缀,next[7]=0

2. 使用next加速匹配

func kmp(s1, s2 string) int {
    if len(s1) < len(s2) {
        return -1
    }
    next := nextArr(s2)
    x, y := 0, 0
    for x < len(s1) && y < len(s2) {
        if s1[x] == s2[y] {
            x++
            y++
        } else if y > 0 {
            y = next[y]
        } else {
            x++
        }
    }
    if y == len(s2) {
        return x - y
    } else {
        return -1
    }
}

3. next数组如何快速生成

func nextArr(s string) []int {
    if len(s) <= 1 {
        return []int{-1}
    }
    next := make([]int, len(s))
    next[0], next[1] = -1, 0
    cp := 0
    for i := 2; i < len(s); {
        if s[i-1] == s[cp] {
            cp++
            next[i] = cp
            i++
        } else if cp > 0 {
            cp = next[cp]
        } else {
            next[i] = 0
            i++
        }
    }
    return next
}

4. 时间复杂度O(m+n)的证明

a) next生成的时间复杂度

// for循环中我们关注i和i-cp
// i的范围是2~m
// i-cp的范围是0~m
// 分支1:i变大, i-cp不变
// 分支2:i-cp变大
// 分支3:i变大,i-cp变大
// 因此时间复杂度O(m)

b) 匹配过程时间复杂度

// for循环中关注x和x-y
// ...
// 同理时间复杂度O(n)

三、例题

1. leetcode#572

[图片上传失败...(image-5964c0-1711559891493)]

// 思路:将两棵树都序列化为sRoot和sSubRoot,然后判断sSubRoot是否为sRoot的子串

func isSubtree(root *TreeNode, subRoot *TreeNode) bool {
    const nullVal = 1e4 + 1
    var s1, s2 []int
    s1 = encode(root, make([]int, 0), nullVal)
    s2 = encode(subRoot, make([]int, 0), nullVal)
    return kmp2(s1, s2) >= 0
}
func encode(root *TreeNode, list []int, nullVal int) []int {
    if root == nil {
        list = append(list, nullVal)
        return list
    }
    list = append(list, root.Val)
    list = encode(root.Left, list, nullVal)
    list = encode(root.Right, list, nullVal)
    return list
}
func kmp2(s1, s2 []int) int {
    if len(s1) < len(s2) {
        return -1
    }
    next := nextArrInt(s2)
    x, y := 0, 0
    for x < len(s1) && y < len(s2) {
        if s1[x] == s2[y] {
            x++
            y++
        } else if y > 0 {
            y = next[y]
        } else {
            x++
        }
    }
    if y == len(s2) {
        return x - y
    } else {
        return -1
    }
}
func nextArrInt(s []int) []int {
    if len(s) <= 1 {
        return []int{-1}
    }
    next := make([]int, len(s))
    next[0], next[1] = -1, 0
    cp := 0
    for i := 2; i < len(s); {
        if s[i-1] == s[cp] {
            cp++
            next[i] = cp
            i++
        } else if cp > 0 {
            cp = next[cp]
        } else {
            next[i] = 0
            i++
        }
    }
    return next
}

2. leetcode#1367

[图片上传失败...(image-a6235b-1711559891493)]

func isSubPath(head *ListNode, root *TreeNode) bool {
    if head == nil {
        return true
    }
    if root == nil {
        return false
    }
    list := make([]int, 0)
    for head != nil {
        list = append(list, head.Val)
        head = head.Next
    }
    next := nextArrInt(list)
    return find(root, list, next, 0)
}

func find(cur *TreeNode, list []int, next []int, index int) bool {
    if index == len(list) {
        return true
    }
    if cur == nil {
        return false
    }
    for index >= 0 && cur.Val != list[index] {
        index = next[index]
    }
    // index=-1 => index=0
    // 匹配 => index+1
    index++
    return find(cur.Left, list, next, index) || find(cur.Right, list, next, index)
}

相关文章

  • 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/rrietjtx.html