RABIN-KARP-MATCHER'(T, P, n, k, m, d, q) h = d^(m - 1) mod q let p[1 : k] be a new array by 0 let T be a new hash-table. t0 = 0 for i = 1 to m t0 = (d * t0 + T[i]) mod q for j = 1 to k p[j] = (d * p[j] + P[j, i]) mod q for j = 1 to k let x be a new node x.key = p[j] x.p = P[j] // 节点x存的是字符串和它的哈希值。 CHAINED-HASH-INSERT(T, x) //假设CHAINED-HASH-SEARCH'返回的是哈希表中和x.key相同的所有节点,而并非只是至多一个;hash是一个哈希函数。 for s = 0 to n - m for v, pat in CHAINED-HASH-SEARCH'(T, hash(t_s)) if v == t_s if pat[1 : m] == T[s + 1 : s + m] print "Pattern " pat " occur with shifts" s if s < n - m t_{s + 1} = (d * (t_s - T[s + 1] * h) + T[s + m + 1]) mod q
RABIN-KARP-MATCHER''(T, P, n, k, d, q) h = d^(m - 1) mod q let p[1 : k] be a new array by 0 let T be a new hash-table. for j = 1 to k t0 = 0 for i = 1 to |P[j]| p[j] = (d * p[j] + P[j, i]) mod q t0 = (d * t0 + T[i]) mod q for s = 0 to n - |P[j]| if p == t_s if P[j, 1 : |P[j]|] == T[s + 1 : s + m] print "Pattern " P[j] " occur with shifts" s if s < n - m t_{s + 1} = (d * (t_s - T[s + 1] * h) + T[s + m + 1]) mod q
RABIN-KARP-MATCHER-2D(T, P, n, m, d, q) ha = d ^ (m * (m-1)) mod q hr = d ^ (m-1) mod q d' = d ^ m mod q p = 0 for j = 1 to m for i = 1 to m p = (d * p + P[i, j]) mod q let U[1 : n] be a new array by 0 for j = 1 to n for i = 1 to m U[j] = (d * U[j] + T[i, j]) mod q for rs = 0 to n - m u0 = 0 for j = 1 to m u0 = (d' * u0 + U[j]) mod q for cs = 0 to n - m if p == ts if P[1 : m,1 : m] == T[rs + 1:rs + m,cs + 1:cs + m] print "Pattern occurs with shift" (rs, cs) if cs < n - m u_{cs + 1} = (d' * (u_{cs} - U[cs + 1] * ha) + U[cs + m + 1]) mod q if rs < n - m for j = 1 to n U[j] = (d * (u[j] - T[rs + 1, j] * ha) + T[rs + m + 1, j]) mod q