尝试获取 KMP 算法中模式的前缀表

问题描述

我正在尝试为字符串匹配实现 KMP 算法,基本上我有我的模式 tenen,需要在特定字符串中搜索让我们假设该字符串为 this is ten in tenen

我正在尝试编写伪代码来创建我的模式的前缀表。我想了解模式 tenen 的前缀表是什么,如果我能得到我们如何得出结果的解释,那就太好了。

解决方法

搜索算法的伪代码描述,来自wikipadia

algorithm kmp_search:
    input:
        an array of characters,S (the text to be searched)
        an array of characters,W (the word sought)
    output:
        an array of integers,P (positions in S at which W is found)
        an integer,nP (number of positions)

    define variables:
        an integer,j ← 0 (the position of the current character in S)
        an integer,k ← 0 (the position of the current character in W)
        an array of integers,T (the table,computed elsewhere)

    let nP ← 0

    while j < length(S) do
        if W[k] = S[j] then
            let j ← j + 1
            let k ← k + 1
            if k = length(W) then
                (occurrence found,if only first occurrence is needed,m ← j - k  may be returned here)
                let P[nP] ← j - k,nP ← nP + 1
                let k ← T[k] (T[length(W)] can't be -1)
        else
            let k ← T[k]
            if k < 0 then
                let j ← j + 1
                let k ← k + 1