#include<iostream>
#include<vector>
#include<string>
using namespace std;
// 最大相等前后缀
int preh(string s) {
int n = s.size();
int j = n-1;
while (j) {
if (s.substr(0, j) == s.substr(n - j , j)) {
break;
}
else {
j--;
}
}
return j;
}
int kmp(string t, string p, vector<int> next) {
int i = 0, j = 0;
while (i<t.size()&&j<p.size()) {
if (t[i] == p[j]||j == -1) {// 当j为-1时,要移动的是i,当然j也要归0
i++;
j++;
}
else {
j = next[j];
}
}
if (j == p.size()) {
return i - j;
}
else {
return -1;
}
}
void main() {
string t = "aabaabaaf";//文本串
string p = "aabaaf";//模式串
vector<int> next;// 公共前后缀
next.push_back(-1);
for (int i = 0; i < p.size(); i++) {
next.push_back(preh(p.substr(0, i + 1)));
}
cout << kmp(t, p, next);
}
KMP算法
最新推荐文章于 2022-11-03 21:50:23 发布