【问题标题】:"Partial match" table (aka "failure function") in KMP (on wikipedia)KMP(在维基百科上)中的“部分匹配”表(又名“失败函数”)
【发布时间】:2013-09-20 08:03:56
【问题描述】:

我正在阅读维基百科上的KMP algorithm。 “建表算法的伪代码描述”部分有一行代码让我很困惑:let cnd ← T[cnd]

它有一条评论:(second case: it doesn't, but we can fall back),我知道我们可以后退,但为什么是 T[cnd],有什么原因吗?因为它真的让我很困惑。

这是建表算法的完整伪代码:

algorithm kmp_table:
    input:
        an array of characters, W (the word to be analyzed)
        an array of integers, T (the table to be filled)
    output:
        nothing (but during operation, it populates the table)

    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 < length(W) do
        (first case: the substring continues)
        if W[pos - 1] = W[cnd] then
            let cnd ← cnd + 1, T[pos] ← cnd, pos ← pos + 1

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

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

【问题讨论】:

    标签: algorithm wikipedia string-matching knuth-morris-pratt


    【解决方案1】:

    您可以回退到T[cnd],因为它包含模式W 的前一个最长专有前缀的长度,这也是W[0...cnd] 的专有后缀。所以如果W[pos-1]的当前字符匹配W[T[cnd]]的字符,你可以延长W[0...pos-1]的最长正确前缀的长度(这是第一种情况)。

    我猜这有点像动态编程,您需要依赖先前计算的值。

    This 解释可能会对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2019-07-20
      • 1970-01-01
      相关资源
      最近更新 更多