若主串S中存在和串T值相同的子串,返回它在主串S中所有出现的位置。
#include <iostream>
#include <string>
using namespace std;
int main()
{
void GetNext(string T,int next[]);
void KMP(string K,string T,int next[]);
int next[] = {0};
string S;
string T;
cout << "请输入主串:\n";
cin >> S;
cout << "请输入子串:\n";
cin >> T;
KMP(S,T,next);
return 0;
}
void GetNext(string T,int next[])
{
int p_len = T.size();
//i匹配后缀
int i=0;
//j匹配前缀
int j=-1;
next[i] = j;
while(i<p_len-1)
{
if(j==-1 || T[i]==T[j])
{
i++;
j++;
next[i]=j;
}
else
{
j=next[j];
}
}
}
void KMP(string K,string T,int next[])
{
GetNext(T,next);
int k_len = K.size();
int t_len = T.size();
//K是主串
//T是子串
int i=0;
int j=0;
//s记录匹配成功的个数
int s=0;
while(i < k_len)
{
if(j==-1 || K[i]==T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
if(j == t_len) //匹配成功
{
cout << "第" << ++s << "对匹配成功!起始位置为" << i-j;
cout << endl;
j=0;
}
}
}