The prefix function,
Following pseudocode computes the prefix fucnction, : Compute-Prefix-Function (p) 1 m length[p] //p pattern to be matched 2 [1] 0 3 k0 4 for q 2 to m 5 do while k > 0 and p[k+1] != p[q] 6 do k [k] 7 If p[k+1] = p[q] 8 then k k +1 9 [q] k 10 return
The KMP Matcher
The KMP Matcher, with pattern p, string S and prefix function as input, finds a match of p in S. Following pseudocode computes the matching component of KMP algorithm: KMP-Matcher(S,p) 1 n length[S] 2 m length[p] 3 Compute-Prefix-Function(p) 4q0 //number of characters matched 5 for i 1 to n //scan S from left to right 6 do while q > 0 and p[q+1] != S[i] 7 do q [q] //next character does not match 8 if p[q+1] = S[i] 9 then q q + 1 //next character matches 10 if q = m //is all of p matched? 11 then print Pattern occurs with shift i m 12 q [ q] // look for the next match Note: KMP finds every occurrence of a p in S. That is why KMP does not terminate in step 12, rather it searches remainder of S for any more occurrences of p.