Knuth–Morris–Pratt algorithm: Difference between revisions

Content deleted Content added
Avhohlov (talk | contribs)
Undo changes 06:43, 27 December 2017‎ Croesnick - no off-by-one error (length(T) = length(W) + 1)
Avhohlov (talk | contribs)
m Variable i renamed to k (for next edit)
Line 135:
'''define variables''':
an integer, m ← 0 (the beginning of the current match in S)
an integer, ik ← 0 (the position of the current character in W)
an array of integers, T (the table, computed elsewhere)
'''let''' nP ← 0
'''while''' m + ik < length(S) '''do'''
'''if''' W[ik] = S[m + ik] '''then'''
'''let''' ikik + 1
'''if''' ik = length(W) '''then'''
(occurrence found, if only first occurrence is needed, m may be returned at this point)
'''let''' P[nP] ← m, nP ← nP + 1
'''let''' m ← m + ik - T[ik], ik ← T[ik] (T[length(W)] can't be -1)
'''else'''
'''let''' ikik + 1
'''else'''
'''if''' T[ik] > -1 '''then'''
'''let''' m ← m + ik - T[ik], ik ← T[ik]
'''else'''
'''let''' m ← m + ik + 1, ik ← 0
 
===Efficiency of the search algorithm===