gpt4 book ai didi

algorithm - 了解使用 LCP 阵列进行模式匹配的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:59:45 25 4
gpt4 key购买 nike

前言:我的问题主要是算法题,所以即使你不熟悉后缀和 LCP 数组,你也可以帮助我。

this论文描述了如何有效地使用后缀和 LCP 数组进行字符串模式匹配。

我了解 SA 和 LCP 的工作原理以及如何从 O(P*log(N)) 改进算法的运行时间(其中 P 是模式的长度N 是字符串的长度)到 O(P+log(N))(感谢 Chris Eelmaa 的回答 here 和 jogojapans 的回答 here)。

我试图通过图 4 中的算法,它解释了 LLcpRLcp 的用法。但我无法理解它的工作原理。

算法(取自 the source ):

Pattern matching algorithm

所用变量名说明:

lcp(v,w) : Length of the longest common prefix of v and w
W = w0..wP-1 : pattern of length P
A = a0..aN-1 : the text (length N)
Pos[0..N-1] : suffix array
L_W : index (in A) of first occurrence of the matched pattern
M : middle index of current substring
L : lower bound
R : upper bound
Lcp : array of size N-2 such that Lcp[M] = lcp(A_Pos[L_M], A_pos[M]) where L_M is the lower bound of the unique interval with M in the middle
Rcp : array of size N-2 such that Rcp[M] = lcp(A_Pos[R_M], A_pos[M]) where R_M is the upper bound of the unique interval with M in the middle

现在我想使用以下示例(部分取自 here )尝试该算法:

 SA | LCP | Suffix entry
-----------------------
5 | N/A | a
3 | 1 | ana
1 | 3 | anana
0 | 0 | banana
4 | 0 | na
2 | 2 | nana

A = "banana" ; N = 6
W = "ban" ; P = 3

我想尝试匹配一个字符串,比如说 ban 并且希望算法返回 0 作为 L_W

下面是我将如何逐步完成算法:

l = lcp("a", "ban") = 0
r = lcp("nana", "ban") = 0
if 0 = 3 or 'b' =< 'a' then // which is NOT the case for both conditions
L_W = 0
else if 0 < 3 or 'b' =< 'n' then // which is the case for both conditions
L_W = 6 // which means 'not found'
...
...

我觉得我错过了什么,但我找不到什么。我还想知道如何使用预先计算的 LCP 数组而不是调用 lcp(v,w)

最佳答案

我相信有一个错误。

第一个条件很容易理解。当 LCP 长度 == 模式长度时,它就完成了。当你的模式甚至小于或等于最小的模式时,那么只能选择最小的模式。

第二个条件错误。我们可以用反证法来证明。 r < P || Wr <= a... 意味着 r >= P && Wr > a... 如果 r >= P,那么我们怎么能有 Lw = N(未找到),因为我们已经有了 r 长度的公共(public)前缀?

关于algorithm - 了解使用 LCP 阵列进行模式匹配的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28444226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com