#include <iostream>
#include <string>
using namespace std;
void getnext(string T, int next[])
{
int i, j, len;
next[0] = -1;
for (int j = 1; T[j] != '\0'; j++) // 依次求next[j]
{
for (len = j - 1; len >= 1; len--) // 相等子串的最大长度为j-1
{
for (i = 0; i < len; i++)
{
if (T[i] != T[j - len + i]) // 比较T[0]~T[len-1]和T[j-len]~T[j-1]是否相等
break;
}
if (i == len)
{
next[j] = len;
break;
}
}
if (len < 1)
{
next[j] = 0; // 其他情况,无相等字串
}
}
}
int KMP(string S, string T)
{
int i = 0, j = 0;
int next[80];
getnext(T, next);
while (S[i] != '\0' && T[j] != '\0')
{
if (S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
if (j == -1)
{
i++;
j++;
}
}
}
if (T[j] == '\0')
return (i - j);
else
return -1;
}
int main()
{
string S;
string T;
cin >> S;
cin >> T;
cout << KMP(S, T);
return 0;
}
KMP算法
最新推荐文章于 2024-07-15 22:10:26 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)