资源 · 指南或文章
Z Algorithm
讲解用 Z 数组进行线性时间的模式搜索,Z 数组的每一项记录从该下标开始的子串与字符串前缀匹配的长度。
审核日期
打开原站: Z Algorithm (在新标签页中打开原网站)练习这个主题以 技术 / 编程 模式打开练习面试官,然后在那里选择题目。
添加到路线图
把这个资源放进你正在跟进的路线图。它会作为你自己的补充资源显示;路线图的步骤不会改变,也不计入你已记录的步骤。
来源内容语言:英语
The Z-algorithm finds occurrences of a "word" W within a main "text string" T in linear time O(|W| + |T|). Given a string S of length n, the algorithm produces an array, Z where Z[i] represents the longest substring starting from S[i] which is also a prefix of S. Finding Z for the string obtained by concatenating the word, W with a nonce character, say $ followed by the text, T, helps with pattern matching, for if there is some index i such that Z[i] equals the pattern length, then the pattern must be present at that point. While the Z array can be computed with two nested loops in O(|W| * |T|) time, the following strategy shows how to obtain it in linear time, based on the idea that as we iterate over the letters in the string (index i from 1 to n - 1), we maintain an interval [L, R] which is the interval with maximum R such that 1 ≤ L ≤ i ≤ R and S[L...R] is a prefix that is also a substring (if no such interval exists, just let L = R = - 1). For i = 1, we can simply compute L and R by comparing S[0...] to S[1...].
PrepKit 概览
本概览由 PrepKit 编辑根据源代码仓库撰写并审核,并非资源本身的文字。
- 适合人群
- 来源未说明适用级别
- 形式
- 参考资料
涵盖内容
- 展示搜索技巧:把模式串、一个分隔符(如 $)和文本拼接起来,然后寻找等于模式串长度的 Z 值
- 介绍使计算保持线性的 [L, R] 区间
- 列出四个 Z 数组示例,包括 aaaaaa 和 abababab
- 给出时间 O(|W| + |T|),空间 O(|W|)
使用建议
这是 PrepKit 的学习建议,并非来源的说法。
手动计算列出示例的 Z 数组,与页面核对,然后编写 [L, R] 版本,并确认它能找到所有模式匹配。
范围与局限
区间更新规则只是粗略带过,Z-box 示意图是外部托管的图片。完整推导在链接的 GeeksForGeeks、YouTube 和博客参考资料中。
获取方式与形式
GitHub 上 trekhleb/javascript-algorithms(MIT)中的 README。英文,免费阅读。
PrepKit 于 2026年10月2日 审核。 资源来源提交: 85293e3e2b88
本概览的依据
- src/algorithms/string/z-algorithm/README.md
收录此条目的页面
订阅 PrepKit 通讯
可选。使用 PrepKit 并不需要订阅。