1 next数组
void getNext(string s){
int j = -1;
next[0] = -1; //初始化:j = next[0] = -1
for (int i = 1; i < s.size(); i++){
while (j != -1 && s[i] != s[j + 1]) {
j = next[j];
}
if (s[i] == s[j + 1]){
j++;
}
next[i] = j;
}
}
2 KMP算法
判断模式串pattern是否出现在文本串text中,时间复杂度O(M+N)
bool KMP(string text, string pattern){
getNext(pattern);
int j = -1;
for (int i = 0; i < text.size(); i++){
while (j != -1 && text[i] != pattern[j + 1]) {
j = next[j];
}
if (text[i] == pattern[j + 1]){
j++;
}
if (j == pattren.size() - 1) return true;
}
return false;
}
统计模式串pattern在文本串中出现的次数,时间复杂度O(M+N)
int KMP(string text, string pattern){
getNext(pattern);
int j = -1, ans = 0;
for (int i = 0; i < text.size(); i++){
while (j != -1 && text[i] != pattern[j + 1]) {
j = next[j];
}
if (text[i] == pattern[j + 1]){
j++;
}
if (j == pattren.size() - 1) {
ans++;
j = next[j];
}
}
return ans;
}
3 字符串模式匹配KMP完整代码
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
const int MAXN = 1000;
int Next[MAXN];
void getNext(string s){
int j = -1;
Next[0] = -1;
for (int i = 1; i < s.size(); i++){ //注意这里是i = 1
while (j != -1 && s[i] != s[j + 1]){
j = Next[j];
}
if (s[i] == s[j + 1]){
j++;
}
Next[i] = j;
}
}
bool KMP(string text, string pattern){
getNext(pattern);
int j = -1;
for (int i = 0; i < text.size(); i++){
while (j != -1 && text[i] != pattern[j + 1]){
j = Next[j];
}
if (text[i] == pattern[j + 1]){
j++;
}
if (j == pattern.size() - 1) return true;
}
return false;
}
int main(){
string text, pattern;
cin >> text >> pattern;
if (KMP(text, pattern)) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
KMP算法详解
本文深入讲解了KMP算法,包括1next数组的构建过程,KMP算法如何在文本串中高效查找模式串,以及如何统计模式串在文本串中出现的次数。提供了完整的C++代码实现,帮助读者理解并掌握KMP算法的原理与应用。
24万+

被折叠的 条评论
为什么被折叠?



