#include<iostream>
#include<string>
using namespace std;
void GetNext(string &str, int next[]){
next[0] = -1;
int i = 0, j = -1;
while (i < str.size()-1){
if (j == -1 || str[i] == str[j]){
++i;
++j;
next[i] = j;
}
else{
j = next[j];
}
}
}
int KMP(string &str1, string &str2,int next[]){
int m = str1.size(), n = str2.size();
GetNext(str2, next);//求next数组
int i = 0, j = 0;
while (i < m && j < n) {
if (j == -1 || str1[i] == str2[j]) {
++i;
++j;
}
else {
j = next[j];
}
}
if (j == n) {
return i - j;//返回模式串在主串的起始位置
}
else {
return -1;//没有找到返回-1
}
}
int main()
{
string str;
string stp;
int next[100];
cin >> str;
cin >> stp;
GetNext(stp, next);
int K = KMP(str, stp, next);
cout << "-1代表没有重合位:" << K << endl;
return 0;
}
KMP(C++)
最新推荐文章于 2023-10-25 23:32:11 发布