KMP算法通过next数组实现主串指针不回退,利用模式串最长公共前后缀信息跳过重复比较,将匹配复杂度降至O(m+n);核心是构建next数组,即对模式串自匹配求每个位置前缀函数值,再用该数组在文本串中滑动匹配,避免暴力回溯。

在C++中实现KMP(Knuth-Morris-Pratt)算法,核心在于利用模式串的“部分匹配表”(即next数组),避免在字符串匹配过程中重复比较已知相同的字符。相比暴力匹配,KMP将时间复杂度从O(mn)优化到O(m+n),适合处理长文本的精确匹配问题。
KMP算法的关键是当主串和模式串在某个位置失配时,不回退主串的指针,而是通过预处理模式串得到的next数组,将模式串向右“滑动”到下一个可能匹配的位置。
重点在于:
next数组的构造本质上是一个“模式串自匹配”的过程。我们用两个指针i和j,其中j表示当前最长前缀的长度,i遍历模式串。
立即学习“C++免费学习笔记(深入)”;
代码示例:
void buildNext(const string& pattern, vector<int>& next) {
int n = pattern.length();
next[0] = 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;
}
}
说明:当pattern[i] != pattern[j]时,j回退到next[j-1],直到匹配或j为0。
使用构建好的next数组,在主串中查找所有模式串出现的位置。
完整匹配函数:
vector<int> kmpSearch(const string& text, const string& pattern) {
vector<int> result;
if (pattern.empty()) return result;
<pre class='brush:php;toolbar:false;'>vector<int> next(pattern.length());
buildNext(pattern, next);
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) {
result.push_back(i - n + 1);
j = next[j - 1]; // 继续找下一个匹配
}
}
return result;}
该函数返回所有匹配起始下标的列表。例如在"ABABDABACDABABCABC"中查找"ABABCAB",会返回对应的索引位置。
简单调用方式:
int main() {
string text = "ABABDABACDABABCABC";
string pattern = "ABABCAB";
vector<int> matches = kmpSearch(text, pattern);
<pre class='brush:php;toolbar:false;'>for (int pos : matches) {
cout << "匹配位置: " << pos << endl;
}
return 0;}
输出结果会显示所有成功匹配的起始索引。
基本上就这些。KMP难点在next数组的理解和构造,一旦掌握,代码其实很简洁。关键是明白为什么能跳过某些比较——因为利用了前缀信息,避免重复劳动。
以上就是C++怎么实现KMP算法_C++字符串匹配算法与KMP实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号