/**
*
* Althor:Hacker Hao
* Create:2023.10.11
*
*/
#include <bits/stdc++.h>
using namespace std;
#define maxn 200
int kmp[maxn];
char t[maxn], p[maxn];
int main()
{
cout << "请输入文本串:" << endl;
cin >> t;
cout << "请输入模式串:" << endl;
cin >> p;
int lent = strlen(t);
int lenp = strlen(p);
//下文中,index表示“指针”,length表示前后缀的最长长度
for (int index = 0, length = 0; index < lenp; index++)
{
while (length && p[length] != p[index])
length = kmp[length];
if (p[length] == p[index])
length++;
kmp[index] = length;
}
for (int index = 0, length = 0; index < lent; index++)
{
while (length && p[length] != t[index])
{
length = kmp[length];
}
if (p[length] == t[index])
length++;
if (length == lenp)
{
cout << index - lenp + 2;
break;
}
}
return 0;
}
C/C++: 数据结构之KMP算法
于 2023-10-16 21:51:22 首次发布