#include<iostream>
using namespace std;
int ne[100] = { 0 };
void ne_ca(string str_M) {
str_M = ' ' + str_M;
for (int i = 2, j = 0; i < str_M.size(); i++) {
while (j && str_M[i] != str_M[j+1]) { j = ne[j]; }
if (str_M[i] == str_M[j+1])j++;
ne[i] = j;
}
}
int KMP(string str_N,string str_M) {
str_N = ' ' + str_N;
str_M = ' ' + str_M;
for (int i = 1,j = 0; i <= str_N.size(); i++) {
while (j && str_N[i] != str_M[j + 1])j = ne[j];
if (str_N[i] == str_M[j + 1])j++;
if (j == str_M.size()-1) {
return i - j;
}
}
return 0;
}
void main() {
string str_N = "abcabcdbcdabbcdbcdabbcdbcdab";
string str_M = "bc";
ne_ca(str_M);
int res = KMP(str_N, str_M);
cout << res;
}
7.KMP算法
最新推荐文章于 2024-08-01 13:27:05 发布