保存时间:2026/4/2 04:27:01
KMP 算法:#include <iostream>
#include <string>
#include <vector>
// 计算 next 数组
void getNext(std::string& pattern, std::vector<int>& next) {
int m = pattern.size();
next.resize(m);
int i = 0, j = -1;
next[0] = -1;
while (i < m - 1) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
// KMP 搜索函数
int kmpSearch(std::string text, std::string pattern) {
int n = text.size(), m = pattern.size();
std::vector<int> next(m);
getNext(pattern, next);
int i = 0, j = 0;
while (i < n && j < m) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == m) {
return i - j;
}
return -1;
}
int main() {
std::string text = "BBC ABCDAB ABCDABCDABDE";
std::string pattern = "ABCDABD";
int index = kmpSearch(text, pattern);
if (index!= -1) {
std::cout << "Pattern found at index: " << index << std::endl;
} else {
std::cout << "Pattern not found" << std::endl;
}
return 0;
}
KMP 算法来在主字符串中搜索子串。getNext 函数用于计算 next 数组,kmpSearch 函数执行实际的搜索操作。<regex> 库来进行正则表达式搜索子串的示例代码:#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "BBC ABCDAB ABCDABCDABDE";
std::string pattern = "ABCDABD";
std::regex regexPattern(pattern);
if (std::regex_search(text, regexPattern)) {
std::cout << "Pattern found" << std::endl;
} else {
std::cout << "Pattern not found" << std::endl;
}
return 0;
}
regexPattern,然后使用 regex_search 函数来检查主字符串 text 中是否存在匹配的子串。getNext 函数的目的是计算模式字符串(子串)的 next 数组。next 数组用于在匹配过程中,当当前字符不匹配时,决定模式字符串应该回溯的位置,以避免不必要的重新比较,从而提高匹配的效率。next 数组存储了模式字符串中每个位置之前的子串的最长前缀和最长后缀相等的长度。通过这个数组,在匹配过程中遇到不匹配时,可以根据当前位置对应的 next 值快速将模式字符串回溯到合适的位置继续比较,而不是每次都从头开始重新比较。#include <iostream>
#include <string>
#include <vector>
// 计算 next 数组
void getNext(std::string& pattern, std::vector<int>& next) {
int m = pattern.size();
next.resize(m);
int i = 0, j = -1;
next[0] = -1;
while (i < m - 1) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
// KMP 搜索函数
int kmpSearch(std::string text, std::string pattern) {
int n = text.size(), m = pattern.size();
std::vector<int> next(m);
getNext(pattern, next); // 调用计算 next 数组的函数
int i = 0, j = 0;
while (i < n && j < m) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == m) {
return i - j;
}
return -1;
}
int main() {
std::string text = "BBC ABCDAB ABCDABCDABDE";
std::string pattern = "ABCDABD";
int index = kmpSearch(text, pattern);
if (index!= -1) {
std::cout << "Pattern found at index: " << index << std::endl;
} else {
std::cout << "Pattern not found" << std::endl;
}
return 0;
}