# 克努斯–莫里斯–普拉特算法

**克努斯–莫里斯–普拉特算法**（Knuth–Morris–Pratt algorithm，简称KMP）是一种字符串匹配算法，它将搜索串转换为一个有限状态机，然后以待搜索的字符串作为输入串来运行该状态机；其执行时间为O(m+n)，其中m是搜索串的长度，n是文本的长度<sup>[1](https://xlinux.nist.gov/dads/HTML/knuthMorrisPratt.html)</sup>。该算法由唐纳德·E·克努斯（Donald E. Knuth）、小詹姆斯·H·莫里斯（James H. Morris, Jr.）和沃恩·R·普拉特（Vaughan R. Pratt）以《字符串中的快速模式匹配》为题发表于《SIAM计算杂志》1977年6月第6卷第2期第323–350页<sup>[2](https://epubs.siam.org/doi/abs/10.1137/0206024)</sup>。

| 关键事实 | 详情 |
|---|---|
| 问题 | 找出长度为n的文本T中长度为m的模式P作为子串出现的所有起始位置<sup>[2](https://epubs.siam.org/doi/abs/10.1137/0206024)</sup> |
| 最坏情况时间 | O(n)扫描；更精确地说，不超过2n − 1次字符比较，证明了里维斯特（Rivest）下界的紧致性<sup>[3](https://cybra.lodz.pl/Content/3528/SzGrabowski-hab.pdf)</sup> |
| 预处理 | 原始的DFA表述构建表格所需的时间和空间与R·M成正比，其中R为字母表大小，M为模式长度；改进的NFA表述仅需与M成正比的空间<sup>[4](https://www.cs.princeton.edu/courses/archive/spr14/cos226/lectures/53SubstringSearch.pdf)</sup> |
| 平均情况 | 对于大小为c的字母表上的随机模式和文本，KMP比较次数与朴素搜索比较次数之比近似为1 − 1/c + 1/c²<sup>[5](https://www.sciencedirect.com/science/article/pii/0020019084900036)</sup> |
| 发表 | 克努斯、莫里斯和普拉特，《字符串中的快速模式匹配》，《SIAM计算杂志》第6卷第2期，第323–350页，1977年6月；斯坦福技术报告CS440于1974年发表<sup>[2](https://epubs.siam.org/doi/abs/10.1137/0206024)</sup> |
| 典型开销 | 在典型输入上约1.1N次字符比较，而暴力搜索的典型开销同为1.1N，暴力搜索的最坏情况为MN<sup>[6](https://www.cs.princeton.edu/courses/archive/spr04/cos226/lectures/string.4up.pdf)</sup> |

## 工作原理

KMP的基本思想是在发生不匹配时避免在文本串中回溯<sup>[3](https://cybra.lodz.pl/Content/3528/SzGrabowski-hab.pdf)</sup>。朴素搜索尝试在文本的每个位置匹配模式，因此当部分匹配失败后，它将模式滑动一个字符并从头重新比较，导致O(nm)的最坏情况行为。KMP则对部分匹配的每个状态预先计算好：当下一个文本字符无法延续匹配时，应从何处继续。美国国家标准与技术研究院（NIST）的《算法与数据结构词典》将这一结果描述为将搜索串转换为一个有限状态机，然后以文本作为输入来运行该状态机<sup>[1](https://xlinux.nist.gov/dads/HTML/knuthMorrisPratt.html)</sup>。

回退信息来自模式本身：对于模式的每个前缀，表中记录的是该前缀的最长真前缀，且该真前缀同时也是该前缀的后缀。当匹配了若干字符后发生不匹配时，算法知道该前缀已经出现在文本中不匹配位置之前，因此可以在对应的状态恢复匹配，而无需重新检查文本字符。由于文本指针从不回退，扫描是对文本的一次从左到右的单遍遍历<sup>[3](https://cybra.lodz.pl/Content/3528/SzGrabowski-hab.pdf)</sup>。

两种表述并存。经典表述构建一个确定性有限自动机（DFA），其转移以字母表字符为索引；塞奇威克（Sedgewick）和韦恩（Wayne）的分析表明，这种构建所需的时间和空间与R·M成正比，而基于带失败链接的非确定性自动机（NFA）的改进版本仅需与M成正比的空间<sup>[4](https://www.cs.princeton.edu/courses/archive/spr14/cos226/lectures/53SubstringSearch.pdf)</sup>。教科书在处理方式上有所不同：科尔曼（Cormen）、莱瑟森（Leiserson）、里维斯特（Rivest）和斯坦（Stein）讲解了较简单的莫里斯–普拉特算法，将克努斯的优化留作习题，而塞奇威克和韦恩则介绍了相关的最小DFA构建<sup>[7](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/knuthmorrispratt-illustrated/8EFA77D663D585B68630E372BCE1EBA4)</sup>。

## 复杂度

KMP的最坏情况运行时间为O(n)；更精确地说，它执行的字符比较不超过2n − 1次，这证明了里维斯特对该问题的下界是紧致的<sup>[3](https://cybra.lodz.pl/Content/3528/SzGrabowski-hab.pdf)</sup>。普林斯顿的分析将该界表述为：在长度为N的文本中搜索长度为M的模式，访问字符不超过M + N个——构建自动机时每个模式字符被访问一次，模拟时每个文本字符至多被访问一次<sup>[4](https://www.cs.princeton.edu/courses/archive/spr14/cos226/lectures/53SubstringSearch.pdf)</sup>。

平均情况已用[马尔可夫链](https://www.edgepedia.org/zh/markov-chain)模型进行分析。格哈德·巴特（Gerhard Barth）将KMP与寻找模式最左出现的直接试错搜索进行比较，证明当模式和文本都是大小为c的字母表上的随机串时，1 − 1/c + 1/c²是KMP比较次数与朴素比较次数之比的一个精确近似<sup>[5](https://www.sciencedirect.com/science/article/pii/0020019084900036)</sup>。在典型输入上，普林斯顿的讲义将KMP的字符比较次数列为约1.1N，与暴力搜索的典型开销相同，决定性的差异在于最坏情况：KMP为2N，而暴力搜索为MN<sup>[6](https://www.cs.princeton.edu/courses/archive/spr04/cos226/lectures/string.4up.pdf)</sup>。

## 历史

该算法的起源颇为不同寻常。普林斯顿的讲义记载，克努斯受到一个深奥定理的启发，从中发现了线性算法<sup>[8](https://www.cs.princeton.edu/courses/archive/fall17/cos226/lectures/53SubstringSearch.pdf)</sup>。2024年《函数式编程杂志》的一篇文章描述了该算法的产生过程：从[斯蒂芬·库克](https://www.edgepedia.org/zh/stephen-cook)（Stephen Cook）的构造性证明出发——该证明表明双向确定性下推自动机所接受的每种语言也可由[随机存取机](https://www.edgepedia.org/zh/random-access-machine)在线性时间内接受——克努斯推导出了算法本身（克努斯等，1977年，第338页）<sup>[7](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/knuthmorrispratt-illustrated/8EFA77D663D585B68630E372BCE1EBA4)</sup>。

这项工作最初以斯坦福技术报告CS440于1974年发表，随后于1977年6月作为SIAM期刊论文发表<sup>[2](https://epubs.siam.org/doi/abs/10.1137/0206024)</sup>。论文本身的历史评注部分描述了该模式匹配算法是“以一种相当有趣的方式被发现的”<sup>[9](https://liacs.leidenuniv.nl/~hoogeboomhj/dat/ohp/dat-notes-24-12-03c.pdf)</sup>。1977年同一卷《SIAM计算杂志》还刊登了罗伯特·博耶（Robert Boyer）和[J·斯特罗瑟·摩尔](https://www.edgepedia.org/zh/j-strother-moore)（J Strother Moore）的竞争性字符串搜索算法，其1975年的手稿早于KMP的期刊版本<sup>[2](https://epubs.siam.org/doi/abs/10.1137/0206024)</sup>。

## 与其他算法的比较

KMP和博耶–摩尔（Boyer–Moore）以不同的权衡解决相同的精确匹配问题。博耶–摩尔由鲍勃·博耶（Bob Boyer）和J·斯特罗瑟·摩尔于1975年前后发明，平均而言是次线性的，即它通常查看的字符数少于它经过的字符数，且其速度随模式长度增长<sup>[10](https://www.cs.utexas.edu/~moore/best-ideas/string-searching/)</sup>。一份模式匹配课程教材指出，博耶–摩尔是精确匹配的实用首选方法，而讲解KMP部分出于历史原因，主要因为它比博耶–摩尔更容易推广到实时字符串匹配和针对模式集合的匹配等问题<sup>[11](https://pages.di.unipi.it/pisanti/DIDATTICA/patternmatching2.pdf)</sup>。经典的博耶–摩尔算法在DNA等小字母表上往往效率不高，因为子串频繁重复导致其跳跃距离不再增长<sup>[10](https://www.cs.utexas.edu/~moore/best-ideas/string-searching/)</sup>。

KMP的保证是单遍扫描文本的线性最坏情况，这使其适用于最坏情况界很重要且模式预处理可接受的场合<sup>[12](https://grasp-it.dev/dsa/lesson/232/string-matching-naive-search-kmp-prefix-function-z-and-rabin-karp/)</sup>。与卡普–拉宾（Karp–Rabin）和博耶–摩尔一样，它带有显著的预处理时间，NIST词典的设计说明在讨论字符串算法时特别指出了这一特性<sup>[13](https://nvlpubs.nist.gov/nistpubs/ir/2020/NIST.IR.8318.pdf)</sup>。

## 应用

KMP的[模式匹配](https://www.edgepedia.org/zh/pattern-matching)用于生物信息学和入侵检测等领域，因其在大规模文本上的快速执行而受到重视<sup>[14](https://pure.konkuk.ac.kr/en/publications/high-throughput-parallel-kmp-algorithm-considering-cpu-gpu-memory/)</sup>。在生物信息学中，KMP和博耶–摩尔在20世纪70年代被用于通过较大序列的精确匹配来定位DNA的共同区域<sup>[15](https://pmc.ncbi.nlm.nih.gov/articles/PMC4296134/)</sup>，KMP至今仍是序列分析教学中标准的精确匹配算法之一<sup>[16](https://citeseerx.ist.psu.edu/document?doi=ab6b49e517aefe3b832dbed6c670a2f82e47e16c&repid=rep1&type=pdf)</sup>。

该算法也能适应新的硬件。2018年，建国大学的朴昭恩（Soeun Park）、金大熙（Daehee Kim）、李明浩（Myungho Lee）和朴能洙（Neungsoo Park）进行了一项研究，使用OpenCL在GPU上实现了并行KMP，优化了工作组分配、模式和失败表的本地内存副本以及数据传输与匹配的重叠；优化后的并行版本运行速度约为未优化的并行KMP的3.6倍<sup>[14](https://pure.konkuk.ac.kr/en/publications/high-throughput-parallel-kmp-algorithm-considering-cpu-gpu-memory/)</sup>。后续工作将KMP方法扩展到了不确定字符串，其中模式和文本位置可能存放字符集合而非单个字符<sup>[17](https://arxiv.org/abs/2204.08331)</sup>。

## References

1. [Sterling Bates, "Knuth-Morris-Pratt algorithm", Dictionary of Algorithms and Data Structures, NIST, ed. Paul E. Black, 26 July 2021](https://xlinux.nist.gov/dads/HTML/knuthMorrisPratt.html)
2. [D. E. Knuth, J. H. Morris, Jr., V. R. Pratt, "Fast Pattern Matching in Strings", SIAM Journal on Computing 6(2):323–350, 1977](https://epubs.siam.org/doi/abs/10.1137/0206024)
3. [Szczepan Grabowski, Online Exact String Matching (habilitation thesis), Lodz University](https://cybra.lodz.pl/Content/3528/SzGrabowski-hab.pdf)
4. [Robert Sedgewick and Kevin Wayne, "String Searching", COS 226 lecture notes, Princeton University](https://www.cs.princeton.edu/courses/archive/spr14/cos226/lectures/53SubstringSearch.pdf)
5. [Gerhard Barth, "An analytical comparison of two string searching algorithms", Information Processing Letters 18(5):249–256, 1984](https://www.sciencedirect.com/science/article/pii/0020019084900036)
6. [Robert Sedgewick, "String Search" lecture notes, COS 226, Princeton University, 2004](https://www.cs.princeton.edu/courses/archive/spr04/cos226/lectures/string.4up.pdf)
7. ["Knuth–Morris–Pratt illustrated", Journal of Functional Programming 34, e3, 2024](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/knuthmorrispratt-illustrated/8EFA77D663D585B68630E372BCE1EBA4)
8. ["Substring Search" lecture notes, COS 226, Princeton University, Fall 2017](https://www.cs.princeton.edu/courses/archive/fall17/cos226/lectures/53SubstringSearch.pdf)
9. [Dat-notes referencing Section 7, Historical remarks, of Knuth, Morris, and Pratt (1977), Leiden University](https://liacs.leidenuniv.nl/~hoogeboomhj/dat/ohp/dat-notes-24-12-03c.pdf)
10. [J Strother Moore, "The Boyer-Moore Fast String Searching Algorithm", University of Texas at Austin](https://www.cs.utexas.edu/~moore/best-ideas/string-searching/)
11. ["Classical Comparison-Based String Matching" course notes, Università di Pisa](https://pages.di.unipi.it/pisanti/DIDATTICA/patternmatching2.pdf)
12. ["String Matching: Naive Search, KMP, Prefix Function, Z, and Rabin-Karp", grasp-it.dev DSA lesson](https://grasp-it.dev/dsa/lesson/232/string-matching-naive-search-kmp-prefix-function-z-and-rabin-karp/)
13. [Paul E. Black et al., "DADS: The On-Line Dictionary of Algorithms and Data Structures", NIST IR 8318, 2020](https://nvlpubs.nist.gov/nistpubs/ir/2020/NIST.IR.8318.pdf)
14. [Soeun Park, Daehee Kim, Myungho Lee, Neungsoo Park, "High throughput parallel KMP algorithm considering CPU-GPU memory hierarchy", Transactions of the Korean Institute of Electrical Engineers 67(5):656–662, 2018](https://pure.konkuk.ac.kr/en/publications/high-throughput-parallel-kmp-algorithm-considering-cpu-gpu-memory/)
15. ["Alignment-free genetic sequence comparisons: a review of recent approaches by word analysis", PMC](https://pmc.ncbi.nlm.nih.gov/articles/PMC4296134/)
16. ["Pattern Matching Algorithms for Bioinformatics", CiteSeerX](https://citeseerx.ist.psu.edu/document?doi=ab6b49e517aefe3b832dbed6c670a2f82e47e16c&repid=rep1&type=pdf)
17. ["Practical KMP/BM Style Pattern-Matching on Indeterminate Strings", arXiv:2204.08331](https://arxiv.org/abs/2204.08331)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Algorithms and computational methods › Numerical, string, and geometric algorithms › String algorithms

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/knuth-morris-pratt-algorithm

English original: https://www.edgepedia.org/knuth-morris-pratt-algorithm
