# 拉宾-卡普算法

拉宾-卡普算法（Rabin–Karp algorithm）是一种随机化[字符串搜索算法](https://www.edgepedia.org/zh/string-searching-algorithm)，由[理查德·M·卡普](https://www.edgepedia.org/zh/richard-m-karp)（Richard M. Karp）与[迈克尔·O·拉宾](https://www.edgepedia.org/zh/michael-o-rabin)（Michael O. Rabin）于1987年发表。该算法通过在文本中比较子串的短滚动哈希指纹，而非逐字符比较字符串，来找出模式串在文本中的出现位置。<sup>[1](https://cir.nii.ac.jp/crid/1361137044594504832)</sup> 其核心装置是滚动哈希，它使得每一个相继的文本窗口的哈希值都能在常数时间内由前一个窗口的哈希值算出，因此扫描整个文本所需的时间与模式串的长度无关。<sup>[2](https://web.eecs.utk.edu/~jplank/plank/classes/cs494/494/notes/RabinKarp/index.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 原始发表 | 理查德·M·卡普与迈克尔·O·拉宾，《高效的随机化模式匹配算法》，《IBM研究与开发杂志》31(2)，第249–260页，1987年3月<sup>[1](https://cir.nii.ac.jp/crid/1361137044594504832)</sup> |
| 核心思想 | 用称为指纹的短得多的字符串来表示长度为 n 的字符串，并操作指纹而非较长的字符串<sup>[3](https://cris.huji.ac.il/en/publications/efficient-randomized-pattern-matching-algorithms/)</sup> |
| 期望时间 | 对于长度为 n 的文本和长度为 m 的模式串，为 O(n + m)，预处理为 Θ(m)；最坏情况为 Θ((n − m + 1)m)，与暴力法相同<sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup> |
| 空间 | 常数个存储位置；原始算法基本上是实时运行的<sup>[3](https://cris.huji.ac.il/en/publications/efficient-randomized-pattern-matching-algorithms/)</sup> |
| 两种模式 | 蒙特卡洛模式（跳过验证，快速但偶尔出错）与拉斯维加斯模式（验证每一次哈希匹配，始终正确，期望线性）<sup>[5](https://dsa.handbook.academy/curriculum/strings-pattern-matching/rabin-karp/)</sup> |
| 错误控制 | 使用模素数 p 的随机多项式哈希时，每次比较的假阳性率至多为 m/p；整个文本上的期望假匹配数至多为 n·m/p<sup>[6](https://www.cs.utexas.edu/~ecprice/courses/randomized/fa19/notes/lec11.pdf)</sup> |
| 扩展 | 可自然推广到二维模式匹配以及同时搜索多个模式<sup>[3](https://cris.huji.ac.il/en/publications/efficient-randomized-pattern-matching-algorithms/)</sup><sup> • </sup><sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup> |

## 工作原理

朴素的子串搜索方法将模式串在文本上滑动，并在每个位置比较字符，最坏情况下代价为 O((n − m + 1)·m)。<sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup> 拉宾-卡普算法用数字上的算术运算取代了这些字符比较。长度为 m 的模式串以及文本中每个长度为 m 的窗口都被视为某个进制下的数，并对素数 q 取模，从而产生一个指纹。<sup>[7](https://www.cs.utexas.edu/~misra/Classes.dir/ClassNotes.dir/337.pdf)</sup> 两个不同的字符串可能产生相同的指纹（碰撞），因此指纹匹配只被当作候选，而非结论。<sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup>

**滚动哈希。** 使该方法高效的一步是 O(1) 的窗口更新。当窗口向右滑动一个位置时，算法移除移出字符的贡献，将每个剩余项提升一个进制幂次，再加入移入字符，形式为 ((oldHash − outChar·base^(m−1)) · base + inChar) mod q，而无需重新检查窗口中间的 m−2 个字符。<sup>[8](https://ucoruh.github.io/ce205-data-structures/week-12/cen207-week-12/)</sup> 由于每次滑动无论模式串长度如何都只需常数次运算，因此在 Θ(m) 的预处理（对模式串和第一个窗口求哈希）之后，扫描全部 n−m+1 个窗口需要 O(n) 次哈希运算。<sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup><sup> • </sup><sup>[2](https://web.eecs.utk.edu/~jplank/plank/classes/cs494/494/notes/RabinKarp/index.html)</sup>

**验证与两种模式。** 当模式串与某个文本窗口的指纹一致时，字符串仍可能不同。拉斯维加斯版本通过在每次哈希匹配时执行暴力字符比较来解决这一问题；它始终正确，运行时间为 O(n + αm)，其中 α 是实际出现的次数。<sup>[6](https://www.cs.utexas.edu/~ecprice/courses/randomized/fa19/notes/lec11.pdf)</sup> 蒙特卡洛版本跳过验证，将每次哈希匹配都报告为匹配；它以 O(m + n) 运行，但偶尔会报告假匹配。<sup>[6](https://www.cs.utexas.edu/~ecprice/courses/randomized/fa19/notes/lec11.pdf)</sup><sup> • </sup><sup>[5](https://dsa.handbook.academy/curriculum/strings-pattern-matching/rabin-karp/)</sup> 1987 年的原始论文命名了这两种模式。<sup>[5](https://dsa.handbook.academy/curriculum/strings-pattern-matching/rabin-karp/)</sup>

## 随机化与错误界

通过随机选择哈希参数，指纹变得可靠。在多项式哈希的表述中，抽取一个随机值 x，字符串 a₁,…,aₘ 的哈希值按 \( \sum_{i=0}^{m-1} a_i \cdot x^{i} \bmod p \) 计算，其中 p 为素数；对于两个不同的字符串，其差是一个次数至多为 m−1 的非零多项式，它至多有 m−1 个根，因此随机 x 发生碰撞的概率至多为 m/p。<sup>[6](https://www.cs.utexas.edu/~ecprice/courses/randomized/fa19/notes/lec11.pdf)</sup> 通过并集界对文本中所有长度为 m 的窗口求和，假匹配的期望数量至多为 n·m/p；取 p > n³ 可将失败率降至至多 1/n。<sup>[6](https://www.cs.utexas.edu/~ecprice/courses/randomized/fa19/notes/lec11.pdf)</sup> 由于 p 被选择为 n 和 m 的多项式界以下，每次模 p 的算术运算都能装入常数个机器字，这正是 O(m + n) 界在标准字模型下成立的原因。<sup>[9](https://www.cs.cmu.edu/~15451-s25/notes/lecture05.pdf)</sup>

另一种表述固定进制，而随机选择模数 p：将两个字符串视为整数，假阳性仅在 p 整除它们的差时发生，该差是一个 (n+1) 位的二进制数，至多有 O(n) 个素因子；在不超过 O(n² log n) 的素数中均匀选取 p，同样可使假阳性率至多为 1/n。<sup>[6](https://www.cs.utexas.edu/~ecprice/courses/randomized/fa19/notes/lec11.pdf)</sup> 随机素数的生成依赖于随机化素性测试，例如米勒-拉宾（Miller–Rabin）测试。<sup>[10](https://homes.cs.washington.edu/~jrl/teaching/cseP531sp16/presentations/pres2.pdf)</sup>

**防范不利抽取。** 一连串的假匹配是运行时间的主要风险，因为每一次假匹配都会触发一次完整的字符比较。

## 复杂度

| 情形 | 时间 |
|---|---|
| 预处理 | 对模式串和第一个窗口求哈希，为 Θ(m)<sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup> |
| 期望（拉斯维加斯，匹配较少） | O(n + m)<sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup> |
| 期望（蒙特卡洛） | O(m + n)<sup>[6](https://www.cs.utexas.edu/~ecprice/courses/randomized/fa19/notes/lec11.pdf)</sup> |
| 最坏情况 | Θ((n − m + 1)m)，当每个窗口的哈希都匹配且每个候选都必须验证时达到<sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup> |
| 空间 | 输入之外为 O(1)<sup>[3](https://cris.huji.ac.il/en/publications/efficient-randomized-pattern-matching-algorithms/)</sup> |

在实际使用中，模式串在大文本中较为罕见，期望时间为 O(n + m)，由于 m ≤ n，即为 O(n)。<sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup>

## 扩展与应用

**多模式。** 指纹结构可自然扩展到一次搜索 k 个等长模式：先对所有 k 个模式各求一次哈希，然后在文本上滚动单个窗口，并在每个位置查询一个模式指纹的哈希集合，得到 O(n + k·m) 的时间和 O(k) 的额外空间。<sup>[5](https://dsa.handbook.academy/curriculum/strings-pattern-matching/rabin-karp/)</sup> 这正是该方法最具竞争力的场景；对于需要严格最坏情况保证的单一模式，更倾向于使用克努特-莫里斯-普拉特（Knuth–Morris–Pratt）等确定性算法，而拉宾-卡普则适合回答诸如成千上万个片段中是否有任何一个出现在某文本中这类问题。<sup>[11](https://prism.nicofortuin.com/algorithms/rabin-karp/)</sup>

**更高维度。** 原始论文指出，该方法可轻松推广到更高维的模式匹配，例如在 n × n 的字符数组中寻找 m × m 的模式。<sup>[3](https://cris.huji.ac.il/en/publications/efficient-randomized-pattern-matching-algorithms/)</sup><sup> • </sup><sup>[4](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)</sup>

**搜索之外的指纹。** 卡普-拉宾指纹是一种具有强代数性质的哈希值，已被复用于各种字符串算法：每符号常数时间的流式字符串匹配、压缩空间中的最长公共扩展查询、文法压缩字符串上的指纹查询，以及通过多层哈希实现的集合参数化匹配。<sup>[12](https://www.researchgate.net/publication/221313695_Real-Time_Streaming_String-Matching)</sup><sup> • </sup><sup>[13](https://arxiv.org/abs/1607.06660)</sup><sup> • </sup><sup>[14](https://arxiv.org/abs/1305.2777)</sup><sup> • </sup><sup>[15](https://arxiv.org/abs/2605.00566)</sup> 搜索算法本身的实用应用包括基于连续词元片段的抄袭检测与近似重复检测。<sup>[11](https://prism.nicofortuin.com/algorithms/rabin-karp/)</sup>

## 实现说明

普林斯顿《算法（第4版）》库中附带了一个参考 Java 实现，即 `RabinKarp` 类，其构造函数对模式串进行预处理，其 `search(String txt)` 方法返回模式串在文本中首次出现的索引。<sup>[16](https://algs4.cs.princeton.edu/code/javadoc/edu/princeton/cs/algs4/RabinKarp.html)</sup> 常见的教学参数是进制 256（每字节一个值）配合诸如 101 的素数模数。<sup>[17](https://www.youtube.com/watch?v=_Rya-4PiHhU)</sup> 实现者必须注意整数宽度：在某些工具链上使用 32 位的 `long` 时，模数 1000000007 与进制 31 组合会产生接近 3.1 × 10¹⁰ 的中间乘积，这会静默地溢出 32 位算术并产生错误答案。<sup>[8](https://ucoruh.github.io/ce205-data-structures/week-12/cen207-week-12/)</sup>

## References

1. [Karp, R. M.; Rabin, M. O. (1987). Efficient randomized pattern-matching algorithms. IBM Journal of Research and Development 31(2), 249–260.](https://cir.nii.ac.jp/crid/1361137044594504832)
2. [Plank, J. CS494 Lecture Notes: The Rabin-Karp String-Searching Algorithm, University of Tennessee.](https://web.eecs.utk.edu/~jplank/plank/classes/cs494/494/notes/RabinKarp/index.html)
3. [Karp, R. M.; Rabin, M. O. (1987). Efficient randomized pattern-matching algorithms, Hebrew University of Jerusalem research portal.](https://cris.huji.ac.il/en/publications/efficient-randomized-pattern-matching-algorithms/)
4. [Suthers, D. Notes on string matching (CLRS Ch. 32), ICS 311, University of Hawaii.](https://courses.ics.hawaii.edu/ReviewICS311/morea/230.string-matching/reading-notes.html)
5. [Rabin-Karp and rolling hashes, The DSA Handbook.](https://dsa.handbook.academy/curriculum/strings-pattern-matching/rabin-karp/)
6. [Price, E. CS 388R: Randomized Algorithms, Lecture 11, UT Austin (2019).](https://www.cs.utexas.edu/~ecprice/courses/randomized/fa19/notes/lec11.pdf)
7. [Misra, J. Class notes: Rabin-Karp algorithm, UT Austin.](https://www.cs.utexas.edu/~misra/Classes.dir/ClassNotes.dir/337.pdf)
8. [Ucoruh, U. CEN207 Data Structures, Week 12: Strings, Rabin-Karp rolling hash and spurious hits.](https://ucoruh.github.io/ce205-data-structures/week-12/cen207-week-12/)
9. [15-451: Algorithm Design and Analysis, Lecture 5, Carnegie Mellon University (2025).](https://www.cs.cmu.edu/~15451-s25/notes/lecture05.pdf)
10. [Karp-Rabin Algorithm Modifications, CSE 531 lecture slides, University of Washington (2016).](https://homes.cs.washington.edu/~jrl/teaching/cseP531sp16/presentations/pres2.pdf)
11. [Rabin–Karp, visualized and explained, Prism.](https://prism.nicofortuin.com/algorithms/rabin-karp/)
12. [Real-Time Streaming String-Matching, ResearchGate.](https://www.researchgate.net/publication/221313695_Real-Time_Streaming_String-Matching)
13. [Fast Longest Common Extensions in Small Space, arXiv:1607.06660.](https://arxiv.org/abs/1607.06660)
14. [Fingerprints in Compressed Strings, arXiv:1305.2777.](https://arxiv.org/abs/1305.2777)
15. [Set Parameterized Matching via Multi-Layer Hashing, arXiv:2605.00566.](https://arxiv.org/abs/2605.00566)
16. [RabinKarp javadoc, Algorithms 4/e, Princeton University.](https://algs4.cs.princeton.edu/code/javadoc/edu/princeton/cs/algs4/RabinKarp.html)
17. [Rabin Karp Algorithm Explained: Rolling Hash, String Matching in Java, ShashCode (YouTube).](https://www.youtube.com/watch?v=_Rya-4PiHhU)

---
*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/rabin-karp-algorithm

English original: https://www.edgepedia.org/rabin-karp-algorithm
