C++版本
#include <iostream>
#include <Cstring>
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);
//KMP("kabcabcpldab","ab",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;
}
}
}
C语言版本
坑先放在这
不知道为什么编译不过
学数据结构本来想写一个String(串)的数据结构,呜呜呜太难了
由衷感叹各种库真是对程序员太好了
#include <stdio.h>
#define MAX 100
typedef struct
{
int length;
char ch[MAX];
}SString;
int main()
{
void GetNext(SString *T,int next[]);
void KMP(SString *K,SString *T,int next[]);
void InitString(SString *S,char *s);
int next[] = {0};
char *S,*V;
printf("请输入主串!\n");
gets(S);
printf("请输入子串!\n");
gets(V);
SString *SS;
SString *VV;
InitString(SS,S);
InitString(VV,V);
KMP(SS,VV,next);
return 0;
}
void GetNext(SString *T,int next[])
{
int p_len = T->length;
//i匹配后缀
int i=0;
//j匹配前缀
int j=-1;
next[i] = j;
while(i<p_len-1)
{
if(j==-1 || T->ch[i]==T->ch[j])
{
i++;
j++;
next[i]=j;
}
else
{
j=next[j];
}
}
}
void KMP(SString *K,SString *T,int next[])
{
GetNext(T,next);
int k_len = K->length;
int t_len = T->length;
//K是主串
//T是子串
int i=0;
int j=0;
//s记录匹配成功的个数
int s=0;
while(i < k_len)
{
if(j==-1 || K->ch[i]==T->ch[j])
{
i++;
j++;
}
else
{
j = next[j];
}
if(j == t_len) //匹配成功
{
printf("第%d对匹配成功!起始位置为%d\n",++s,i-j);
j=0;
}
}
}
void InitString(SString *S,char *s)
{
int i=0;
char *temp = s;
while(*temp)
{
i++;
}
S->length = i;
//S->ch = new char[i+1];
i=0;
while(*s)
{
S->ch[i] = s[i];
}
}