kmp算法总结
#include<iostream>
#include<string.h>
using namespace std;
int next1[1005];
void getnext(char *s1, char *s2)<font color=#70f3ff>难点+重点->next数组的计算</font>
{
int len2 = strlen(s2);
int i = 0, j = -1;
next1[0] = -1;
while (i < len2)
{
if (s2[i] == s2[j] || j == -1)
{
i++;
j++;
next1[i] = j;
}
else
{
j = next1[j];
}
}
}
int kmp(char *s1, char *s2)
{
int i, j;
int len1 = strlen(s1);
int len2 = strlen(s2);
for (i = 0, j = 0; i < len1&&j < len2;)
{
if (s1[i] == s2[j] || j == -1)
{
i++;
j++;
}
else
{
j = next1[j];
}
}
if (j == len2)
{
return i - j;
}
else
{
return -1;
}
}
int main()
{
char s1[1005], s2[1005];
cin >> s1 >> s2;
getnext(s1, s2);
int i = kmp(s1, s2);
cout << i << endl;
return 0;
}
KMP算法就是在一个模板字符串中找一个目标字符串出现的位置,如果出现就返回它的位置,然后没有出现就返回-1
这个链接是大佬对KMP的讲解:
blog.csdn.net/v_july_v/ar…