
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































Jaehyun Park Stanford UniversityCS 97SI
June 30, 2015
String Matching Problem Hash Table Knuth-Morris-Pratt (KMP) Algorithm Suffix Trie Suffix Array
String Matching Problem 2
◮ (^) P appears three times in T ◮ (^) A naive method takes O ( mn ) time
◮ (^) We can do much better!
String Matching Problem 4
String Matching Problem Hash Table Knuth-Morris-Pratt (KMP) Algorithm Suffix Trie Suffix Array
Hash Table 5
◮ (^) Main idea: preprocess T to speedup queries
◮ (^) For each query P , hash the first k letters of P to retrieve all the occurrences of it within T ◮ (^) Don’t forget to check collisions!
Hash Table 7
◮ (^) Pros:
◮ (^) Cons: – Doesn’t help the asymptotic efficiency ◮ (^) Can still takedifficult Θ( nm ) time if hashing is terrible or data is
Hash Table 8
◮ (^) A linear time (!) algorithm that solves the string matchingproblem by preprocessing P in Θ( m ) time
Knuth-Morris-Pratt (KMP) Algorithm 10
◮ (^) π is a suffix of[ i ] is the largest integer smaller than P i such that P 1_... Pπ_ [ i ]
Knuth-Morris-Pratt (KMP) Algorithm 11
◮ (^) We matched k = 3 letters so far, and π [ k ] = 0
◮ (^) Mismatch at T 4 again!
Knuth-Morris-Pratt (KMP) Algorithm 13
◮ (^) We matched k = 0 letters so far ◮ (^) Shift P by k − π [ k ] = 1 letter (we define π [0] = − 1 )
◮ (^) Mismatch at T 11!
Knuth-Morris-Pratt (KMP) Algorithm 14
◮ (^) Mismatch at T 11 again!
◮ (^) Currently 2 letters are matched ◮ (^) Shift P by 2 − π [2] = 2 letters
Knuth-Morris-Pratt (KMP) Algorithm 16
◮ (^) Mismatch at T 11 yet again!
◮ (^) Currently no letters are matched ◮ (^) Shift P by 0 − π [0] = 1 letter
Knuth-Morris-Pratt (KMP) Algorithm 17
◮ (^) Finally, there it is!
◮ (^) Currently all 7 letters are matched ◮ (^) After recording this match (atorder to find other matches T 16_... T_ 22 , we shift P again in
Knuth-Morris-Pratt (KMP) Algorithm 19
◮ (^) Observation 1: if P P 1_... Pπ_ [ i ] is a suffix of P 1_... Pi_ , then (^1) –... P Well, obviously... π [ i ]− 1 is a suffix of^ P 1_... Pi_ − 1 ◮ (^) Observation 2: all the prefixes of P P that are a suffix of (^1) –... P e.g.i , (^) can be obtained by recursively applying P 1_... Pπ_ [ i ], P 1_... , Pπ_ [ π [ i ]], P 1_... , Pπ_ [ π [ π [ i ]]]^ π are all^ to^ i suffixes of P 1_... Pi_
Knuth-Morris-Pratt (KMP) Algorithm 20