KMP算法
下面的代码是可以运行的,拿回去研究研究吧
#include <iostream>
#include <string>
using namespace std;
#define Max 30
void GetNext(string T, int next[], int length)
{
next[0] = -1;
int k = -1, j = 0;
while (j <= length)
{
if (k == -1 || T[k] == T[j])
{
j++;
k++;
next[j] = k;
}
else
{
k = next[k];
}
}
}
int KMP(string S, string T, int Slength, int Tlength)
{
int next[Max];
int i = 0, j = 0;
GetNext(T, next, Tlength);
while (i < Slength && j < Tlength)
{
if (j == -1 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j >= Tlength)
{
return (i - Tlength);
}
else
{
return -1;
}
}
int main()
{
string S, T;
cout << "please input two string" << endl;
cin >> S;
cin >> T;
int SL = S.length();
int TL = T.length();
cout << KMP(S, T, SL, TL) << endl;
}
运行截图