KMP-Matcher(T, P) n = length(T) m = length(P) = Compute-Prefix-Function(P) ; O(m) amortized q = 0 for i = 1 to n ; O(n) amortized while q > 0 and P[q+1] T[i] ; where do we move to in P? q = [q] if P[q+1] = T[i] ; matches so far then q = q + 1 if q = m then print ``Pattern occurs with shift'' (i-m) q = [q]
Example