lec16 - Introduction to Algorithms 6.046J/18.401J Lecture...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Introduction to Algorithms 6.046J/18.401J Lecture 16 Prof. Piotr Indyk
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Introduction to Algorithms April 10, 2003 L16.2 © Piotr Indyk String Matching • Input: Two strings T[1…n] and P[1…m] , containing symbols from alphabet Σ • Goal: find all “shifts” 1 s n-m such that T[s+1…s+m]=P Example: Σ ={ ,a,b,…,z} – T[1…18]= “to be or not to be” – P[1. .2]= “be” – Shifts: 3, 16
Background image of page 2
Introduction to Algorithms April 10, 2003 L16.3 © Piotr Indyk Simple Algorithm for s 0 to n-m Match 1 for j 1 to m if T[ s+j ] P[ j ] then Match 0 exit loop if Match= 1 then output s
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Introduction to Algorithms April 10, 2003 L16.4 © Piotr Indyk Results Running time of the simple algorithm: – Worst-case: O(nm) – Average-case (random text): O(n) Is it possible to achieve O(n) for any input ? – Knuth-Morris-Pratt’77: deterministic – Karp-Rabin’81: randomized
Background image of page 4
Introduction to Algorithms April 10, 2003 L16.5 © Piotr Indyk Karp-Rabin Algorithm A very elegant use of an idea that we have encountered before, namely… HASHING ! Idea: – Hash all substrings T[1…m], T[2…m+1], T[3…m+2], etc. – Hash the pattern P[1…m] – Report the substrings that hash to the same value as P Problem: how to hash n-m substrings, each of length m , in O(n) time ?
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 18

lec16 - Introduction to Algorithms 6.046J/18.401J Lecture...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online