Docsity

Rabin Karp String Search-String Algorithm Design and Analysis-Lecture Slides, Slides of Design and Analysis of Algorithms

Partial preview of the text

Download Rabin Karp String Search-String Algorithm Design and Analysis-Lecture Slides and more Slides Design and Analysis of Algorithms in PDF only on Docsity!

Rabin karp string search

Karp-Rabin

• • Slower for Single pattern matchFast for Multiple pattern match

• Trick is Hash compare.

  • Hmm. These two hash values are the same, so we need to do a stringcomparison between "bca" and "cab". Are they the same? No. So wecontinue:

• Hash value of “AAAAA” is 37 Rabin-Karp Example

• Hash value of “AAAAH” is 100

How it works

  • Hash pattern P into a numeric value – Let a string be represented by the sum of

these digits • Horner’s rule (§ 30.1)

  • Example • { A, B, C, ..., Z } → { 0, 1, 2, ..., 26 }
    • • BANCARD → 1 + 0 + 13→ 2 + 0 + 17 + 3 = 14= 22
  • Problem Upper limits
  • Solution^ –^ For long patterns, or for large alphabets, the numberrepresenting a given string may be too large to be practical
  • Example^ –^ –^ Use MOD operationWhen MOD q, values will be < q
    • BAN • • 14 mod 13 = 1BAN → 1 = 1 + 0 + 13 = 14
    • CARD • • 22 mod 13 = 9CARD → 9 = 2 + 0 + 17 + 3 = 22

RABIN-KARP-MATCHER( T, P, d, q ) n ← length[ T ] Code

m h p ← 0 ← d← length[ P ]m-1 (^) mod q t for 0 ← 0 i ← 1 do p ← ( dp + P[ i ] ) mod q to m ► Preprocessing for s ← 0 do if^ t^0 p = t to ← ( dt ns – m^0 + T[ i ] ) mod q ► Matching if s < n^ then if – m^ then^ P[ 1..m ] = T[ s+1 .. s+m ]^ print “Pattern occurs with shift” s then ts+1 ← ( d * ( ts – T[ s + 1 ] * h ) + T[ s + m + 1 ] ) mod q

Performance of Rabin-Karp

• The worst-case running time of the Rabin- Karp algorithm is O(m (n-m+1))

• Preprocessing (determining each patternhash)

Θ( m )