KMP算法和Z算法的关系算法、关系、KMP

2023-09-11 03:23:40 作者:心安勿忘

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".