STRING ALGORITHMS
Print this page
 
Algorithm for KMP string matcher
 
KMP string matching first preprocesses the given pattern P to compute FailureFunction. Then the output of the FailureFunction is used to skip some of the invalid comparisons. Note that the preprocessing is done once for each pattern. Since in general the size of the pattern to be searched is relatively small, it takes far less time than the string matching process.
             

KMP stringMatch (T, P)

 
  1. n = stringlength[T]
  2. m=length[P]
  3. FF = FailureFunction(P)
  4. j 0
  5. for i 1 to n
  6. while j>0 and P[j+1] T[ i ]
  7. jFF[j]
  8. if P[ j+1 ] = = T[ i ]
  9. then j = j+1
  10. if j = = m
  11. then print "Pattern found with shift " i - m
  12. j = FF[j]

KMP algorithm runs in optimal time O(m+n) time.

   
 
Prev