KMP算法和Z算法的关系

编程入门 行业动态 更新时间:2024-10-28 18:27:04
本文介绍了KMP算法和Z算法的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

KMP 和以Z 算法是众所周知的字符串搜索算法,

KMP and Z algorithms are well known algorithms for string searching,

KMP 算法都是通过它定义为一个KMP故障功能(拍是搜索寻找模式模式)

KMP algorithm deals with finding the patterns through a KMP failure function which is defined as (pat being the searching pattern)

LPS [I] =畏首畏尾[0..i]最长适当preFIX这也是拍拍[0..i]后缀。

lps[i] = the longest proper prefix of pat[0..i] which is also a suffix of pat[0..i].

例如,对于字符串abcab这将是 [0,0,0,1,2]

在这里为以Z 算法使用其定义为Z轴功能:

where as Z algorithm uses the z function which is defined as:

由于长度为n的字符串S,Z轴算法产生阵Z其中Z [i]为从拍[我]开始的最长子串的长度,这也是拍拍的preFIX。

Given a string S of length n, the Z Algorithm produces an array Z where Z[i] is the length of the longest substring starting from pat[i] which is also a prefix of pat.

现在的问题是,我们可以通过使用 KMP 算法的实现以Z 功能? 我所寻找的是 LPS 阵列,导致同样的结果在某些修改 Z [I] 数组。

Now the question is can we achieve the Z function by the use of KMP algorithm? What I am searching for is some modifications in the lps array that leads to the same results as the Z[i] array.

推荐答案

注意:算法是错误的

for i in range(0, len(s)): if lps[i] != 0: Z[i - lps[i] + 1] = lps[i]

之后在 Z [I] 将是最大长度的后缀,在位置开始我并且这也是串的preFIX

After that in Z[i] will be the maximum length of the suffix, that starts in position i and which is also a prefix of the string.

修改

由于nikhil_vyas指出,该算法不能解决你的问题。什么它实际上是部分填充以Z 阵列最长后缀和其他一些人。这种不完整的阵列基本上可以帮你解决几个发现,在字符串中最长的东西的问题,但它不回答你的问题。

As nikhil_vyas noted, the proposed algorithm does not solve your problem. What it actually does is partially filling Z array with the longest suffixes and some others. Such incomplete array can basically help you to solve several "find the longest something in the string" problems, but it does not answer your question.

最简单的方法来重建以Z 阵列,有 LPS 数组,在我脑海是建立字符串,对应 LPS 数组,然后建立以Z 数组的字符串。但我不知道它是否适合你了 LPS 数组中的一些修改的定义。

The easiest way to rebuild Z array having lps array that comes to my mind is to build the string, corresponding to the lps array and then build Z array for that string. But I am not sure whether it suits your definition of "some modifications in the lps array".

更多推荐

KMP算法和Z算法的关系

本文发布于:2023-11-29 23:48:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   关系   KMP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!