Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Knuth–Morris–Pratt algorithm
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Description of pseudocode for the table-building algorithm=== <!--Note to future editors: please do not replace or even supplement the pseudocode with language-specific code. Following the WikiProject Computer Science manual of style, pseudocode is preferred over real code unless the real code illustrates a feature of the language or an implementation detail. This algorithm is so simple that neither of these can ever be the case--> <!--This code appears to implement the table for the Morris-Pratt algorithm, not for the Knuth-Morris-Pratt Algorithm. The KMP table has bigger shifts. See http://www-igm.univ-mlv.fr/~lecroq/string/node8.html--> The example above illustrates the general technique for assembling the table with a minimum of fuss. The principle is that of the overall search: most of the work was already done in getting to the current position, so very little needs to be done in leaving it. The only minor complication is that the logic which is correct late in the string erroneously gives non-proper substrings at the beginning. This necessitates some initialization code. '''algorithm''' ''kmp_table'': '''input''': an array of characters, W (the word to be analyzed) '''output''': an array of integers, T (the table to be filled) '''define variables''': an integer, pos ← 1 (the current position we are computing in T) an integer, cnd ← 0 (the zero-based index in W of the next character of the current candidate substring) '''let''' T[0] ← -1 '''while''' pos < length(W) '''do''' '''if''' W[pos] = W[cnd] '''then''' '''let''' T[pos] ← T[cnd] '''else''' '''let''' T[pos] ← cnd '''while''' cnd ≥ 0 '''and''' W[pos] ≠ W[cnd] '''do''' '''let''' cnd ← T[cnd] '''let''' pos ← pos + 1, cnd ← cnd + 1 '''let''' T[pos] ← cnd (only needed when all word occurrences are searched)
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)