这是一个简单的算法,可以在 O((m+n)*log(m+n)) 内完成,与 O(m+n) 运行时间的后缀树算法相比,实现起来要容易得多。
让它从最小公共长度 (minL) = 0 和最大公共长度 (maxL) = min(m+n)+1 开始。
1. if (minL == maxL - 1), the algorithm finished with common len = minL.
2. let L = (minL + maxL)/2
3. hash every substring of length L in S, with key = hash, val = startIndex.
4. hash every substring of length L in T, with key = hash, val = startIndex. check if any hash collision in to hashes. if yes. check whether whether they are really common substring.
5. if there're really common substring of length L, set minL = L, otherwise set maxL = L. goto 1.
剩下的问题是如何在 O(n) 时间内散列所有长度为 L 的子串。您可以使用如下多项式公式:
Hash(string s, offset i, length L) = s[i] * p^(L-1) + s[i+1] * p^(L-2) + ... + s[i+L-2] * p + s[i+L-1]; choose any constant prime number p.
then Hash(s, i+1, L) = Hash(s, i, L) * p - s[i] * p^L + s[i+L];