Knuth-Morris-Pratt Algorithm (cont)
KMPMatch(T,P):
| Input text T of length n, pattern P of length m
| Output starting index of a substring of T equal to P
| -1 if no such substring exists
|
| F=failureFunction(P)
| i=0, j=0 // start from left
| while i<n do
| | if T[i]=P[j] then
| | | if j=m-1 then
| | | return i-j // match found at i-j
| | | else
| | | i=i+1, j=j+1 // keep comparing
| | | end if
| | else if j>0 then // mismatch and j>0?
| | | j=F[j-1] // → shift pattern to i-F[j-1]
| | else // mismtach and j still 0?
| | | i=i+1 // → begin at next text character
| | end if
| end while
| return -1 // no match
|
|