#include <iostream>
#include <cstring>
using namespace std;
int *getNext(const char *T,int len)
{
int i = 0;
int j = -1;
int *next = new int[len];
next[0] = -1;
while(i < len - 1)
{
if(j == -1 || T[i] == T[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
return next;
}
int KMP(const char *S,const char *T)
{
int i = 0;
int j = 0;
int lens = strlen(S);
int lent = strlen(T);
int *next = getNext(T,lent);
while(i < lens && j < lent)
{
if(j == -1 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
delete[] next;
if(j == lent)
return i - lent;
return -1;
}
int main()
{
char S[100],T[100];
cin >> S >> T;
cout << KMP(S,T) + 1 << endl;
return 0;
}
KMP算法C++实现
最新推荐文章于 2023-08-30 17:54:14 发布