KMP 里面的部分匹配表构造哪位能解释一下第二层的循环吗?

2020-05-10 01:47:34 +08:00
 qwertyegg
fun partialMatchTable(pattern: String): IntArray{
    var pmt = IntArray(pattern.length)
    var j = 0
    for(i in 1 until pattern.length){
    	//下面这个循环怎么理解?
        while(j > 0 && pattern[j] != pattern[i])
            j = pmt[j - 1]        
        pmt[i] = if(pattern[j] == pattern[i]) ++j else j
    }
    return pmt
}

在 SO( https://stackoverflow.com/questions/38757553) 上有一个解释:

"if b[i] = j, then for any k < j, s.t P[0..k-1] == P[i-k..i-1], we know that b[j] >= k. At the same time, obviously b[i] > b[j] or b[i] = 0.

What this means is that we can easily enumerate the k values from largest to smallest, by going through b[i] -> b[b[i]] -> b[b[b[i]]]... and so on. "

说实话没有太看懂. 部分匹配表 /next 表 /SO 上面的 b,都是一个东西

1100 次点击
所在节点    问与答
1 条回复
QingchuanZhang
2020-05-10 06:12:56 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/670153

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX