KMP算法:
next计算
0 1 2 3 4 5 6 7 8
sub A B C D A B C F X
next -1 0 0 0 0 1 2 3 0 指前面有多少个匹配相同
第0位为标记位-1,第1位为0;
第2位对应前一位字符B,next为0,B和A(sub[0])进行比较不相同,置为0;
第3位对应前一位字符C,next为0,
C和A(sub[0])进行比较不相同,置为0;
第4位对应前一位字符D,next为0,D和A(sub[0])进行比较不相同,置为0;
第5位对应前一位字符A,next为0,A和A(sub[0])进行比较相同,置为1;
第6位对应前一位字符B,next为1,B和B(sub[1])进行比较相同,置为2;
第7位对应前一位字符C,next为2,C和C(sub[2])进行比较相同,置为3;
第8位对应前一位字符F,next为3,F和D(sub[3])进行比较不相同,
此时next[3]=0,则F和A(sub[0])进行比较不相同,置为0;
next数组是指在当前substr[j]匹配失败时从子串的第next[j]个字符开始重新匹配,
-1指代跳转,即第一个都不匹配,此处数组以下标0开始,下标以1开始的只需每个加1即可。
实现:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
vector<int> generateNext(const string &s)
{
vector<int> next(s.size(),-1); //第一位为标记位
for (int i = 0,j = -1; i < s.size()-1;)
{
if (j==-1||s[i]==s[j]) //j为第一个未匹配上标志
next[++i] = ++j;
else
j = next[j];
}
return next;
}
int kmp(const string &s1,const string &s2)
{
vector<int> next = generateNext(s2);
int i=0,j=0;
int size1 = s1.size();
int size2 = s2.size();
while(i<=size1&&j<size2)
{
if (j==-1||s1[i]==s2[j]) //第一个未匹配上或字串相匹
{
++i,++j;
}
else
{
j = next[j];
}
}
return j==size2?i-j:-1;
}
int main()
{
string s1,s2;
while (cin>>s1>>s2)
{
cout<<kmp(s1,s2)<<endl;
}
}