1. 程式人生 > >Robin-Karp algorithm 字串的匹配

Robin-Karp algorithm 字串的匹配

有關字串的匹配問題,有很好的演算法,即KMP演算法,但是還有一種其實經常使用到的演算法是Rabin-Karp演算法,它是使用hash的原理來進行字串匹配的。具體的做法如下。

Rabin-Karp演算法是由Rabin和Karp提出的一個在實際中有比較好應用的字串匹配演算法,此演算法的預處理時間為O(m),但它的在最壞情況下的時間複雜度為O((2n-m+1)m),而平均複雜度接近O(m+n),此演算法的主要思想就是通過對字串進行哈稀運算,使得演算法可以容易的排除大量的不相同的字串,假設模式字串的長度為m,利用
Horner法則p = p[m] + 10(p[m -1] + 10(p[m-2]+...+10(p[2]+10p[1])...)),求出模式字串的哈稀值p,而對於文字字串來說,對應於每個長度為m的子串的哈稀值為t(s+1)=10(t(s)-10^(m-1)T[s+1])+T[s+m+1],然後比較此哈稀值與模式字串的哈稀值是否相等,若不相同,則字串一定不同,若相同,則需要進一步的按位比較,所以它的最壞情況下的時間複雜度為O(mn)。

Rabin-Karp is a good example of a randomized algorithm(if we pick M in some random way).We get no guarantee the algorithm runs in O(n+m)time, because we may get unlucky and have the hash values regularly collide with spurious mathces. Still, the odds are heavily in out favor-if the hash function returns values uniformly from 0 to M-1, the probability of a false collision should be 1/M.This is quite reasonable:ifM=.n,there should only be one false collision per string.and if M = n^k for k>=2, the odds are greate we will never see any false collisions.