next up previous
Next: Knuth-Morris-Pratt Algorithm Up: CSE 2320: Algorithms and Previous: String Matching

Naive String Matching

Naive(T, P)
   n = length(T)
   m = length(P)
   for s = 0 to n-m                     O(n-m+1)
      if P[1..m] = T[s+1..s+m]              O(m)
      then print "Pattern occurs with shift" s

This algorithm takes O((n-m+1)m) time.

However, there is more information in a failed match:

T: a a a a b a a ...
P: a a a a a      

s = s + m
No need to consider

Copyright © 1998 The University of Texas at Arlington