有str1 与 str2,要在str1中找到与str2完全相等的子串
1.为了跟有效的找该字符串是否在另外一个字符串里
2.kmp首先用来计算str2的每个下标next值,我们用一个整形数组保存下来,next数组保存的是每一个与自己当前不匹配时str2的下标要移到哪里与str1去比较,可以减少比较的复杂度
3.问题是next数组如何得到
next数组第一个通常符0因为第一个字符前没有字符
我们是得到在该字符前的一串字符他们的最长前后缀是多少
例:ababc
c的next是3因为 ab =ab
#include <iostream>
using namespace std;
void getnext(string t, int next[])
{
int i, j;
i = 1;
j = 0;
next[1] = 0;
while (i < t[0])
{
if (j == 0 || t[j] == t[i]) //当j=0时:代表第一个字符、该最长相同子串为1或者字符相等
{
i++; //后缀
j++; //前缀
next[i] = j;
}
else
j = next[j]; //回溯
}
}
int index_KMP(string s, string t, int pos)
{
int i = pos;
int j = 1;
int next[255]; //得到下标
getnext(t, next);
while (i <= s[0] && j <= t[0]) //i为主串的下标,j为子串的下标
{
if (j == 0 || s[i] == t[j]) //主串与子串下标相等
{
i++;
j++;
}
else
j = next[j]; //j退回
}
if (j > t[0])//子串在主串中
return i - t[0];
else
return 0;
}