24 COMP 6651 B Jaumard Fall 2013 The failure function F 33 Input String P

24 comp 6651 b jaumard fall 2013 the failure function

This preview shows page 24 - 28 out of 28 pages.

24 COMP 6651 – B. Jaumard – Fall 2013 The failure function F (3/3) Input: String P (pattern) with m characters Output: The failure function F for P , which maps j to the length of the longest prefix of P that is a suffix of P[1..j] F[0] 0 ; i 1 ; j 0 While i < m do If P[i] = P[j] then <* we have matched j+1 characters *> F[i] j+1 ; i i+1 ; j j+1 Else If j > 0 then <* j indexes just after a prefix of P that must match *> j F[j-1] Else <* no match *> F[i] 0 ; i i+1 Endif Endif Endwhile
Image of page 24
25 COMP 6651 – B. Jaumard – Fall 2013 Example T : P : a a b c a b a a c a c b a a c b a b a a b b a a a a b c a b 1 3 2 4 5 6 7 a a b c a b a a b c a b a a b c a b i 0 1 2 3 4 5 F 0 0 1 0 1 2 14 16 15 17 18 19 13 8 10 9 11 12 a a b c a b
Image of page 25
26 COMP 6651 – B. Jaumard – Fall 2013
Image of page 26
27 COMP 6651 – B. Jaumard – Fall 2013 Complexity A character of T may be compared against many characters of P. If there is a mismatch, then the same character of T is compared against the character of P pointed by the next table. If there is another mismatch , then we continue comparing against the same character of T until there is either a match or we reach the beginning of P . How many times can we backtrack for one character of T ? Let us assume that the first mismatch involved p k . Since each backtrack leads us to a smaller index in P , we can backtrack only k times. However, to reach p k we must have gone forward k times without any backtracking! If we assign the costs of backtracking to the forward moves, then we at most double the cost of the forward moves. But there are exactly n forward moves, so the number of comparisons is O(n).
Image of page 27
28 COMP 6651 – B. Jaumard – Fall 2013 Questions ?
Image of page 28

You've reached the end of your free preview.

Want to read all 28 pages?

  • Fall '09
  • String searching algorithm, Knuth–Morris–Pratt algorithm

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes