KMP算法通过构建next数组实现高效字符串匹配,利用最长相等前后缀信息避免主串指针回溯,在O(n+m)时间内完成搜索。

KMP(Knuth-Morris-Pratt)算法是一种高效的字符串匹配算法,能够在O(n + m)时间内完成模式串在主串中的查找,避免了暴力匹配中不必要的回溯。其核心思想是利用已匹配的部分信息,通过预处理模式串构造“部分匹配表”(即next数组),跳过不可能匹配的位置。
理解KMP的核心:next数组
在KMP算法中,关键在于构建模式串的next数组,它记录了模式串每个位置之前的最长相等前后缀长度。当发生失配时,可以借助next数组决定模式串应向右滑动多少位,而无需回退主串指针。
例如,模式串 "ABABC" 的 next 数组为:
[0, 0, 1, 2, 0]
构建next数组的过程本质上是一个“模式串自我匹配”的过程,使用双指针技巧:
- i 遍历模式串从 1 到 len-1
- j 表示当前最长相等前后缀的长度,初始为 0
- 若 pattern[i] == pattern[j],则 next[i++] = ++j
- 否则回退 j = next[j-1](如果 j > 0),直到匹配或 j=0
构建next数组的代码实现
void buildNext(const string& pattern, vector& next) { int n = pattern.length(); next.resize(n, 0); int j = 0; // 最长相等前后缀的长度 for (int i = 1; i < n; ++i) { while (j > 0 && pattern[i] != pattern[j]) { j = next[j - 1]; } if (pattern[i] == pattern[j]) { ++j; } next[i] = j; } }
KMP主匹配过程
有了next数组后,主串与模式串的匹配就可以线性进行。主串指针不回退,只移动模式串指针。
立即学习“C++免费学习笔记(深入)”;
- i 遍历主串,j 遍历模式串
- 字符相等时,i++,j++
- 失配时,若 j > 0,则 j = next[j-1];否则 i++
- 当 j 达到模式串长度时,说明找到一次匹配,记录位置并继续搜索
vectorkmpSearch(const string& text, const string& pattern) { vector matches; vector next; buildNext(pattern, next); int n = text.length(); int m = pattern.length(); int j = 0; // 模式串匹配位置 for (int i = 0; i < n; ++i) { while (j > 0 && text[i] != pattern[j]) { j = next[j - 1]; } if (text[i] == pattern[j]) { ++j; } if (j == m) { matches.push_back(i - m + 1); // 记录起始位置 j = next[j - 1]; // 继续查找下一个匹配 } } return matches;}
完整使用示例
#include#include #include using namespace std; int main() { string text = "ABABDABACDABABCABC"; string pattern = "ABABC";
vectorresult = kmpSearch(text, pattern); cout zuojiankuohaophpcnzuojiankuohaophpcn "Pattern found at positions: "; for (int pos : result) { cout zuojiankuohaophpcnzuojiankuohaophpcn pos zuojiankuohaophpcnzuojiankuohaophpcn " "; } cout zuojiankuohaophpcnzuojiankuohaophpcn endl; return 0; }
输出结果为:
Pattern found at positions: 8
表示模式串首次出现在主串第8个位置(从0开始)。基本上就这些。KMP的关键在于理解next数组的意义和构建逻辑,一旦掌握,匹配过程非常清晰高效。










