KMP算法通过构建next数组实现高效字符串匹配,先预处理模式串得到最长相等前后缀信息,再利用该表在主串中跳过无效比较,最终在O(m+n)时间内完成匹配。

在C++中实现KMP(Knuth-Morris-Pratt)算法,核心是通过预处理模式串生成一个部分匹配表(通常称为next数组),利用该表在匹配失败时跳过不必要的比较,从而提高字符串匹配效率。整个过程分为两步:构建next数组、进行主串与模式串的匹配。
next数组记录模式串每个位置之前的最长相等前后缀长度。这个信息用于在匹配失败时决定模式串应向右滑动多少位。
具体做法是从左到右遍历模式串,使用两个指针 i 和 j,其中 j 表示当前最长前缀的长度:
使用构建好的next数组,在主串中查找模式串出现的位置。同样使用双指针技术:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <vector>
#include <string>
<p>std::vector<int> buildNext(const std::string& pattern) {
int n = pattern.length();
std::vector<int> next(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;
}
return next;
}</p><p>std::vector<int> kmpSearch(const std::string& text, const std::string& pattern) {
std::vector<int> matches;
if (pattern.empty()) return matches;</p><pre class='brush:php;toolbar:false;'>auto next = buildNext(pattern);
int m = text.length();
int n = pattern.length();
int j = 0;
for (int i = 0; i < m; ++i) {
while (j > 0 && text[i] != pattern[j]) {
j = next[j - 1];
}
if (text[i] == pattern[j]) {
++j;
}
if (j == n) {
matches.push_back(i - n + 1);
j = next[j - 1]; // 准备下一次匹配
}
}
return matches;}
int main() { std::string text = "ABABDABACDABABCABC"; std::string pattern = "ABABCAB"; auto result = kmpSearch(text, pattern);
for (int pos : result) {
std::cout << "Pattern found at index " << pos << std::endl;
}
return 0;}
上述代码中,buildNext函数生成next数组,kmpSearch函数返回所有匹配位置。时间复杂度为O(m+n),空间复杂度O(n),适合处理长文本中的高效模式匹配。
基本上就这些。掌握next数组的构造逻辑和匹配过程中的状态转移,就能灵活应用KMP算法解决实际问题。
以上就是c++++中如何实现KMP算法_c++ KMP算法实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号