#include<iostream>
#include<string.h>
using namespace std;
void GetNext(char *p,int next[]);
int KmpMatch(char *s,char *p,int next[]);
int main()
{
char *p = new char;
char *s = new char;
cin.getline(s,100);
cin.getline(p,100);
int temp[100];
// Next函数值计算
GetNext(p,temp);
// KMP匹配执行
cout<<KmpMatch(s,p,temp)<<endl;
return 0;
}
void GetNext(char *p,int temp[])
{
int pLen = strlen(p);
int i = 0;
int j = -1;
temp[0] = -1;
while(i < pLen-1)
{
if (j == -1 || p[i] == p[j])
{
i++;
j++;
if (p[i] != p[j])
{
temp[i] = j;
}
else
{
temp[i] = temp[j];
}
}
else
{
j = temp[j];
}
}
}
int KmpMatch(char *s,char *p,int temp[])
{
int sLen = strlen(s);
int pLen = strlen(p);
int i = 0;
int j = 0;
while (i < sLen && j < pLen)
{
if (j== -1 || s[i] == p[j])
{
i++;
j++;
}
else
{
j = temp[j];
}
}
if (j == pLen)
{
return i-j;
}
else {
return -1;
}
}
KMP算法实现
最新推荐文章于 2023-04-09 14:15:00 发布