Abstract
The naive algorithm to search for a pattern within a string compares corresponding characters from left to right, and in case of a mismatch, shifts one position along and starts again. The worst-case time is .
Knuth–Morris–Pratt exploits the knowledge gained from the partial match, never re-comparing characters that matched and thereby achieving linear time. At the first mismatched character, it shifts as far to the right as safely possible. To do so, it consults a precomputed table, based on the pattern . The KMP algorithm is proved correct.
License
Topics
Related publications
- Knuth, D. E., Morris, Jr., J. H., & Pratt, V. R. (1977). Fast Pattern Matching in Strings. SIAM Journal on Computing, 6(2), 323–350. https://doi.org/10.1137/0206024
- Wikipedia