KMP算法的作用是在一个已知字符串中查找子串的位置,也叫做串的模式匹配。
核心在于求next数组
在这里主串s,子串t的下标都从1开始算起
int len1, len2;//字符串s,t的长度
char s[10000], t[10000];
void getnext(char t[],int* next)//求next数组
{
int len = sizeof(t) / sizeof(t[1]);
next[1] = 0;
int i = 1, j = 0;
while (i < len)
{
if (j == 0 || t[i] == t[j])
next[++i] = ++j;
else
j = next[j];
}
}
int KMP(char s[], char t[])//KMP算法
{
int i = 1, j = 1;
int* next = new int[len2 + 1];
getnext(t,next);
while (i <= len1 && j <= len2)
{
if (j == 0 || s[i] == t[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j > len2)
return i - len2;//返回子串在主串中匹配的位置
else
return -1;//没有匹配返回-1
}
int main()
{
cin >> len1 >> len2;
cin >> s+1 >> t+1;//下标从1开始输入
cout << KMP(s, t) << endl;
return 0;
}