Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 关于KMP中预处理表的困惑_String_Algorithm - Fatal编程技术网

String 关于KMP中预处理表的困惑

String 关于KMP中预处理表的困惑,string,algorithm,String,Algorithm,查看KMP算法,并对KMP中计算后缀前缀计数表的特定行感到困惑 算法kmp_表: 输入: 一个字符数组,W(要分析的单词) 整数数组,T(要填充的表) 输出: 无(但在操作过程中,它填充表格) 以上内容直接取自维基百科。如果cnd>0为什么设置cnd:=T[cnd],我有点困惑,cnd不应该像我们再次开始一样重置为0吗?显然,T[0]=-1所以将cnd设置为T[cnd=0]=-1就等于在下一次迭代中读取W[cnd=-1],这超出了字符串范围。至少出于这个原因,您需要对cnd>0vscnd==0进

查看KMP算法,并对KMP中计算后缀前缀计数表的特定行感到困惑

算法kmp_表: 输入: 一个字符数组,W(要分析的单词) 整数数组,T(要填充的表) 输出: 无(但在操作过程中,它填充表格)


以上内容直接取自维基百科。如果
cnd>0
为什么设置
cnd:=T[cnd]
,我有点困惑,cnd不应该像我们再次开始一样重置为0吗?

显然,
T[0]=-1
所以将
cnd
设置为
T[cnd=0]=-1
就等于在下一次迭代中读取
W[cnd=-1]
,这超出了字符串范围。至少出于这个原因,您需要对
cnd>0
vs
cnd==0
进行特殊处理

我们将
cnd
与0进行比较的真正原因是
T[cnd]
应该为我们提供
W[]
中的位置,当
W[cnd]
左侧有一个部分字符串匹配时,该位置应该倒带<但是,code>T[0]不能用于此目的,因为
W[0]
左侧没有任何内容

为什么设置cnd:=T[cnd],cnd不应该重置回0,就像我们再次启动一样

你错过了算法的全部要点。如果在部分匹配后在位置0处重新启动,则返回原始算法
T[]
包含倒带位置,正如您可以从下面带有
W[]
T[]
的示例表中看到的,倒带位置并不总是0。因此,您有时会转到其他位置并从那里继续匹配,而不是一路返回到位置0。这就是为什么该算法比原始算法更具可扩展性

define variables:
    an integer, pos ← 2 (the current position we are computing in T)
    an integer, cnd ← 0 (the zero-based index in W of the next 
    character of the current candidate substring)

(the first few values are fixed but different from what the algorithm 
might suggest)
let T[0] ← -1, T[1] ← 0

while pos is less than the length of W, do:
    (first case: the substring continues)
    if W[pos - 1] = W[cnd], 
      let cnd ← cnd + 1, T[pos] ← cnd, pos ← pos + 1

    (second case: it doesn't, but we can fall back)
    otherwise, if cnd > 0, let cnd ← T[cnd]

    (third case: we have run out of candidates.  Note cnd = 0)
    otherwise, let T[pos] ← 0, pos ← pos + 1