复习一哈:KMP算法_青岛大学_王卓https://www.bilibili.com/video/BV1nJ411V7bd?p=67
结果:
源码用到了c++中的string类
C++——String类https://blog.csdn.net/qq_22046265/article/details/123733246?spm=1001.2014.3001.5502
源码:
#include <iostream>
using namespace std;
void main()
{
int KMP(string S, string T);
void GetNext(string T, int next[]);
int KMPVal(string S, string T);
void GetNextVal(string T, int nextval[]);
//声明
string Sstr{"@"};
string Tstr(Sstr);
//初始化,下标0位 不参与查找 有效数据从小标1开始
Sstr += {"agendahuaidan"};
Tstr += {"dan"};
//给 模式串和子串赋值
cout << "待查找串为" << Sstr << endl << "查找串" << Tstr << endl;
//next数组查找
int key = KMP(Sstr, Tstr);//查找
if (key)
{
cout << "默认KMP:查找串在待查找串的第" << key << "位" << endl;;
}
else
{
cout << "未查找的到!" << endl;
}
//nextval数组查找
int key_val = KMPVal(Sstr, Tstr);//改进查找
if (key_val)
{
cout << "改进KMP:查找串在待查找串的第" << key_val << "位"<<endl;
}
else
{
cout << "未查找的到!" << endl;
}
return ;
}
void GetNext(string T,int next[])
{
int i = 1,j=0;
next[0] = -1;
next[1] = 0;
while (i<T.size())
{
if (j==0||T[i]==T[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int KMP(string S, string T)
{
int i = 1, j = 1;
int next[100];
GetNext(T, next);//得到next数组
while (i<S.size()&&j<T.size())
{
if (j == 0 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j > T.size() - 1)
{
return i - (T.size()-1);//成功
}
else
{
return 0;//匹配失败
}
}
void GetNextVal(string T,int nextval[])
{
int i = 1,j=0;
nextval[1] = 0;
while (i<T.size()-1)
{
if (j==0||T[i]==T[j])
{
i++;
j++;
if (T[i] != T[j])
{
nextval[i] = j;
}
else
{
nextval[i] = nextval[j];
}
}
else
{
j = nextval[j];
}
}
}
int KMPVal(string S, string T)
{
int i = 1, j = 1;
int nextval[100];
GetNextVal(T,nextval);//得到next数组
while (i < S.size() && j < T.size())
{
if (j == 0 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = nextval[j];
}
}
if (j > T.size() - 1)
{
return i - (T.size() - 1);//成功
}
else
{
return 0;//匹配失败
}
}