# 字符串搜索算法

字符串搜索算法在较长的文本串中查找模式串的出现位置。这项任务也称为精确字符串匹配、字符串搜索或文本搜索，是[计算](https://www.edgepedia.org/zh/computing)机科学的经典问题之一：给定长度为 n 的文本 `T` 和长度为 m 的模式 `P`（二者均定义在某个字母表上），报告 `P` 作为 `T` 的连续子串出现的每一个位置（位移）。<sup>[1](https://xlinux.nist.gov/dads/HTML/stringMatching.html)</sup><sup> • </sup><sup>[2](https://arxiv.org/abs/1012.2547)</sup>

| 关键事实 | 详情 |
|---|---|
| 问题 | 找出所有满足：对模式中每个位置 j 都有 T[s + j] = P[j] 的有效位移 s；一个更简单的变体只要求找出第一次出现的位置<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup><sup> • </sup><sup>[4](https://www.cs.cornell.edu/courses/cs312/2002fa/lectures/lec26.htm)</sup> |
| 朴素算法 | 尝试每一个位移并逐字符比较；最坏情况时间为 O((n − m + 1)·m)，当模式和文本都由同一个字符大量重复构成时，复杂度为平方级<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup><sup> • </sup><sup>[4](https://www.cs.cornell.edu/courses/cs312/2002fa/lectures/lec26.htm)</sup> |
| Knuth–Morris–Pratt（1977） | 利用在 O(m) 时间内从模式预计算出的前缀函数，达到线性时间 O(n + m)；它建立在 1970 年 Morris–Pratt 算法的基础之上，后者是第一个达到 O(n) 最坏情况下界的算法<sup>[5](https://epubs.siam.org/doi/abs/10.1137/0206024)</sup><sup> • </sup><sup>[2](https://arxiv.org/abs/1012.2547)</sup> |
| Boyer–Moore（1977） | 从模式的末尾开始匹配，利用坏字符规则和好后缀规则向前跳跃；实际应用中呈亚线性，通常检查的字符数少于它越过的字符数<sup>[6](https://www.cs.utexas.edu/~moore/best-ideas/string-searching/)</sup> |
| Rabin–Karp | 用滚动哈希筛选候选位置；最坏情况为 O((n − m + 1)·m)，但平均情况下快得多，并且可以自然地推广到多模式搜索<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup> |
| 文献规模 | 自 1970 年以来已提出 80 多种算法，其中一半以上出现在 2010 年之前的十年间<sup>[2](https://arxiv.org/abs/1012.2547)</sup> |

## 问题

输入是长度为 n 的文本 `T` 和长度为 m 的模式 `P`，二者都是有限字母表 Σ 上的字符串。如果对模式中每个有效位置 j 都有 `T[s + j] = P[j]`，则称模式在位移 s 处出现；这样的 s 称为有效位移，而字符串匹配问题就是找出所有有效位移。<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup> 例如，在文本“ABABABAC”中，模式“BAB”出现在位移 1 和 3 处。<sup>[4](https://www.cs.cornell.edu/courses/cs312/2002fa/lectures/lec26.htm)</sup>

根据哪个字符串先到达，可以区分两种设定。在在线字符串匹配中，模式是预先已知的，文本在到达时被扫描；基于字符比较、自动机或位并行的算法解决这一版本。在离线字符串匹配中，文本先已可用，可以被预处理成后缀树或后缀数组之类的索引，使得之后每次模式查询都变成在该索引中的一次搜索。<sup>[2](https://arxiv.org/abs/1012.2547)</sup><sup> • </sup><sup>[7](https://cs.uef.fi/pub/Reports/A-2007-1.pdf)</sup> 对于需要频繁搜索的大型集合，从倒排索引出发可能比反复扫描快得多，尽管构建起来更为复杂。<sup>[1](https://xlinux.nist.gov/dads/HTML/stringMatching.html)</sup>

这个问题之所以重要，是因为它支撑着日常软件：文本编辑器、Unix 工具 grep、信息检索系统、网页浏览器和爬虫、图书馆目录以及电话查号服务，都是在较大的文本体中搜索字符串。<sup>[8](https://www.inf.ufes.br/~berilhes/Cursos/TBO2008-1/gusfield.pdf)</sup> 在生物信息学中，精确字符串匹配用于在 DNA 序列中搜索特定模式，其字母表是四个字母 {A, C, G, T}。<sup>[9](https://www.uni-ulm.de/fileadmin/website_uni_ulm/iui.inst.190/Mitarbeiter/ohlebusch/Enno_Ohlebusch_Bioinformatics_Algorithms.pdf)</sup>

## 朴素方法

基线算法将模式沿文本每次滑动一个位置，在每个对齐处比较对应字符，在第一个不匹配处即中止。<sup>[4](https://www.cs.cornell.edu/courses/cs312/2002fa/lectures/lec26.htm)</sup> 其最坏情况运行时间为 O((n − m + 1)·m)，当模式长度约为文本长度的一半时，这就是文本长度的平方级；由单个重复字符大量构成的文本和模式会触发这种行为。<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup><sup> • </sup><sup>[4](https://www.cs.cornell.edu/courses/cs312/2002fa/lectures/lec26.htm)</sup> 对于短模式，朴素方法是可以接受的，并且它仍然是更快的算法所改进的参照点。<sup>[4](https://www.cs.cornell.edu/courses/cs312/2002fa/lectures/lec26.htm)</sup>

## 线性时间算法：KMP 与自动机

Knuth–Morris–Pratt（KMP）算法由 Donald E. Knuth、James H. Morris, Jr. 和 Vaughan R. Pratt 于 1977 年在《SIAM Journal on Computing》上发表，它在与两个字符串长度之和成正比的时间 O(n + m) 内找出模式的所有出现位置，且不在文本中回退。<sup>[5](https://epubs.siam.org/doi/abs/10.1137/0206024)</sup> 它在 O(m) 时间内从模式预计算出一个前缀函数；该表编码了模式与自身各位移的匹配方式，使算法能够避免朴素方法会无谓尝试的那些位移。<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup> 这一成果建立在 Morris 和 Pratt 1970 年的一份技术报告之上，该报告提出的算法是第一个达到该问题 O(n) 最坏情况下界的算法。<sup>[2](https://arxiv.org/abs/1012.2547)</sup>

一个相关的表述是从模式构建字符串匹配自动机：一个有限自动机，其状态记录迄今读入的文本中最长的、同时又是模式前缀的后缀的长度。这样的自动机对每个文本字符恰好检查一次，每字符花费常数时间，因此构建完成后的扫描代价为 O(n)；当字母表很大时，构建本身可能代价高昂，KMP 通过即时计算等价信息避免了这一点。<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup>

## 向前跳跃：Boyer–Moore 及其家族

Boyer–Moore 算法由 Robert S. Boyer 和 J. Strother Moore 约于 1975 年发明，1977 年发表在《Communications of the ACM》上，它采取相反的策略：从模式的末尾而非开头开始匹配。<sup>[6](https://www.cs.utexas.edu/~moore/best-ideas/string-searching/)</sup><sup> • </sup><sup>[10](https://cir.nii.ac.jp/crid/1361699995558729216?lang=en)</sup> 当发生不匹配时，坏字符规则将模式移动，使不匹配的文本字符与其在模式中最近的出现位置对齐，如果该字符在模式中不出现则完全越过它；好后缀规则利用已匹配的部分进一步移动。<sup>[4](https://www.cs.cornell.edu/courses/cs312/2002fa/lectures/lec26.htm)</sup><sup> • </sup><sup>[11](https://www.ijcaonline.org/archives/volume187/number53/gor-2025-ijca-925896.pdf)</sup> 这些移动使算法能够跳过文本的若干区段，从而在平均情况下呈现亚线性行为，尽管其最坏情况并不比朴素算法更好。<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup> Moore 描述了这样一个反直觉的特性：模式越长，算法往往越快，因为它通常查看的字符少于它越过的字符。<sup>[6](https://www.cs.utexas.edu/~moore/best-ideas/string-searching/)</sup>

Boyer–Moore 启发了大量变体。简化的 Horspool 版本（1980）和 Sunday 的 Quick Search 算法（1990）是实践中最高效的基于比较的方法之一，尽管它们具有平方级的最坏情况。<sup>[12](https://igm.univ-mlv.fr/~lecroq/articles/acmsurv2013.pdf)</sup> 1995 年的实验结果表明，对于大字母表和短模式，Sunday 的 Quick Search 最为高效；而对于小字母表和长模式，Crochemore 及其同事的 Reverse Factor 算法最为高效。<sup>[13](https://onlinelibrary.wiley.com/doi/abs/10.1002/spe.4380250703)</sup> 在 DNA 这样的小字母表上，经典算法失去了优势，因为子串频繁重复，跳跃距离不再随模式长度增长；记住更多已匹配的内容可以恢复更大的跳跃，代价是需要非常大的表或状态机。<sup>[6](https://www.cs.utexas.edu/~moore/best-ideas/string-searching/)</sup>

## 哈希与位并行

Rabin–Karp 算法与 KMP 和 Boyer–Moore 一同出现在 1977 年的同一部教科书论述中，它用模式以及文本中每个长度为 m 的窗口的滚动哈希来筛选候选对齐位置。其最坏情况为 O((n − m + 1)·m)，与朴素方法相同，但平均情况下表现好得多，并且可以自然地推广到其他模式匹配问题，包括同时搜索多个模式；哈希冲突如果频繁发生，会使性能退化回平方级界限。<sup>[3](https://bobson.ludost.net/books/algo/book6/chap34.htm)</sup><sup> • </sup><sup>[11](https://www.ijcaonline.org/archives/volume187/number53/gor-2025-ijca-925896.pdf)</sup>

位并行算法在机器字的各个位中模拟一个非确定性自动机。Baeza-Yates 和 Gonnet 的 Shift-Or 算法（1992）以及 Navarro 和 Raffinot 的后向非确定性 DAWG 匹配（BNDM）算法（1998）是标准范例；BNDM 对于短模式尤其高效。<sup>[12](https://igm.univ-mlv.fr/~lecroq/articles/acmsurv2013.pdf)</sup> 现代多模式匹配器用 SIMD 指令进一步推进了这一方向：Hyperscan 是一款面向服务器 CPU 的高性能正则表达式匹配器，它将正则表达式分解为字符串匹配和有限自动机匹配，并用 SIMD 操作加速二者，在真实流量轨迹上将 Snort 入侵检测系统的性能提升至原来的 8.7 倍。<sup>[14](https://www.usenix.org/conference/nsdi19/presentation/wang-xiang)</sup>

## 多模式匹配与常数空间算法

在网络安全中，多字符串模式匹配是深度包检测中更昂贵的正则表达式匹配的前提条件。<sup>[14](https://www.usenix.org/conference/nsdi19/presentation/wang-xiang)</sup>

另一条研究路线最小化的是内存而非时间。常数空间字符串匹配旨在设计只使用常数额外空间的算法；其两个主要的经典算法是 Galil–Seiferas 算法（1983）和 Maxime Crochemore 与 Dominique Perrin 的 Two-Way 算法（1991），后者可以看作 KMP 与 Boyer–Moore 之间的中间形态。<sup>[12](https://igm.univ-mlv.fr/~lecroq/articles/acmsurv2013.pdf)</sup><sup> • </sup><sup>[15](https://www.cin.ufpe.br/~paguso/courses/if767/bib/Crochemore_1991.pdf)</sup> 双向方法具有实际影响：CPython 的 `str.find` 使用 Crochemore–Perrin 双向算法，它具有与 KMP 一样的线性最坏情况时间和 O(1) 空间，并叠加了一张 Boyer–Moore 风格的坏字符表以在典型文本上实现亚线性跳跃，还会根据观察到的比较次数自适应地切换策略。<sup>[16](https://www.ironclad.academy/dsa/techniques/string-matching)</sup>

## 理论怎么说

在线字符串匹配的最坏情况下界是 O(n)，因为每个字符都可能需要被检查，而 Morris–Pratt 一系的算法达到了这一下界。<sup>[2](https://arxiv.org/abs/1012.2547)</sup> 对于字母等概率且独立的随机文本，[Andrew Yao](https://www.edgepedia.org/zh/andrew-yao) 于 1979 年证明了 O(n log m / m) 的平均下界，表明亚线性平均行为在原理上是可能的；许多算法——其中首推 Boyer–Moore——的设计目标就是在实践中接近亚线性性能。<sup>[2](https://arxiv.org/abs/1012.2547)</sup><sup> • </sup><sup>[12](https://igm.univ-mlv.fr/~lecroq/articles/acmsurv2013.pdf)</sup>

没有哪一种算法占据主导地位。卡塔尼亚大学的 Simone Faro 和鲁昂大学的 Thierry Lecroq 所做的全面实验评估发现，算法性能在不同字母表大小和模式长度下差异显著，后来的综述将该领域分为基于比较、基于自动机、位并行、常数空间和实时等家族。<sup>[2](https://arxiv.org/abs/1012.2547)</sup><sup> • </sup><sup>[12](https://igm.univ-mlv.fr/~lecroq/articles/acmsurv2013.pdf)</sup> 因此选择取决于工作负载：模式长度、字母表大小、文本是流式还是已建索引，以及寻找的是单个模式还是多个模式。

## 相关问题

精确匹配是更广泛家族中最简单的成员。带错误的字符串匹配，或称[近似字符串匹配](https://www.edgepedia.org/zh/approximate-string-matching)，允许有限数量的不匹配、插入或删除，而 Myers 的位向量算法为基因组学和 OCR 处理中的此类噪声数据提供了快速方法。<sup>[1](https://xlinux.nist.gov/dads/HTML/stringMatching.html)</sup><sup> • </sup><sup>[11](https://www.ijcaonline.org/archives/volume187/number53/gor-2025-ijca-925896.pdf)</sup> 当文本本身巨大且被反复查询时，后缀树和后缀数组之类的索引取代了扫描：后缀数组是指向文本各后缀的指针的有序数组，因此一次模式查询就变成在该数组中的二分搜索。<sup>[1](https://xlinux.nist.gov/dads/HTML/stringMatching.html)</sup><sup> • </sup><sup>[7](https://cs.uef.fi/pub/Reports/A-2007-1.pdf)</sup>

## References

1. [Paul E. Black, "string matching", Dictionary of Algorithms and Data Structures, NIST](https://xlinux.nist.gov/dads/HTML/stringMatching.html)
2. [Simone Faro and Thierry Lecroq (2010). The Exact String Matching Problem: a Comprehensive Experimental Evaluation. arXiv:1012.2547](https://arxiv.org/abs/1012.2547)
3. [Introduction to Algorithms, Chapter 34: String Matching](https://bobson.ludost.net/books/algo/book6/chap34.htm)
4. [CS312 Lecture 26: String search, Cornell University](https://www.cs.cornell.edu/courses/cs312/2002fa/lectures/lec26.htm)
5. [Knuth, Morris, Pratt (1977). Fast Pattern Matching in Strings. SIAM Journal on Computing 6(2):323–350](https://epubs.siam.org/doi/abs/10.1137/0206024)
6. [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/)
7. [Exact string matching and indexing, University of Eastern Finland report A-2007-1](https://cs.uef.fi/pub/Reports/A-2007-1.pdf)
8. [Dan Gusfield, Exact String Matching (chapter), applications of string matching](https://www.inf.ufes.br/~berilhes/Cursos/TBO2008-1/gusfield.pdf)
9. [Enno Ohlebusch, Bioinformatics Algorithms, chapter 2: Exact String Matching](https://www.uni-ulm.de/fileadmin/website_uni_ulm/iui.inst.190/Mitarbeiter/ohlebusch/Enno_Ohlebusch_Bioinformatics_Algorithms.pdf)
10. [Boyer, R.S. and Moore, J.S. (1977). A fast string searching algorithm. Communications of the ACM 20(10):762–772](https://cir.nii.ac.jp/crid/1361699995558729216?lang=en)
11. [Survey of string matching algorithm development, International Journal of Computer Applications](https://www.ijcaonline.org/archives/volume187/number53/gor-2025-ijca-925896.pdf)
12. [Faro and Lecroq, The Exact Online String Matching Problem: a Review and an Experimental Evaluation (ACM Computing Surveys draft)](https://igm.univ-mlv.fr/~lecroq/articles/acmsurv2013.pdf)
13. [Thierry Lecroq (1995). Experimental results on string matching algorithms. Software: Practice and Experience 25(7):727–765](https://onlinelibrary.wiley.com/doi/abs/10.1002/spe.4380250703)
14. [Wang, Hong, Chang, Park, Langdale, Hu, Zhu (2019). Hyperscan: A Fast Multi-pattern Regex Matcher for Modern CPUs. NSDI '19](https://www.usenix.org/conference/nsdi19/presentation/wang-xiang)
15. [Crochemore and Perrin (1991). Two-Way String-Matching](https://www.cin.ufpe.br/~paguso/courses/if767/bib/Crochemore_1991.pdf)
16. [String Matching: KMP and Rabin-Karp Without the Mysticism, Ironclad Academy](https://www.ironclad.academy/dsa/techniques/string-matching)

---
*Initially written Sep 17, 2026 · Reviewed: 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/string-searching-algorithm

English original: https://www.edgepedia.org/string-searching-algorithm
