#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define Sizemax 200
#define Status int
typedef struct
{
char* ch;
int Length;
}SString;
Status InSString(SString& S, SString& T)
{
S.ch = new char[Sizemax];
T.ch = new char[Sizemax];
S.Length = Sizemax;
T.Length = Sizemax;
return OK;
}
Status shuru(SString& S, SString& T)
{
char* p;
p = (char*)malloc(sizeof(char));
p = S.ch;
p++;
scanf_s("%s",p,Sizemax-1);
S.Length=strlen(S.ch);
printf("S字符串输入完毕\n");
p = T.ch;
p++;
scanf_s("%s",p,Sizemax-1);
T.Length = strlen(T.ch);
printf("T字符串输入完毕\n");
return OK;
}
Status Display(SString S, SString T)
{
char* p;
p = (char*)malloc(sizeof(char));
p = S.ch;
p++;
printf("S字符串为:%s\n",p);
p = T.ch;
p++;
printf("T字符串为:%s\n",p);
return OK;
}
Status Get_next(SString S,SString T,int next[])//C语言可以传数组
{
int i, j;
i = 1;
j = 0;
next[1]=0;
while (j < T.Length)
{
if (S.ch[i] == T.ch[j]||j==0)//这里不讲究顺序,j等于0不必要写在前面
{
++i; ++j;
next[i] = j;
}
else j=next[j];
}
return OK;
}
Status Get_nextval(SString S,SString T,int nextval[])
{
int i, j;
i = 1;
j = 0;
nextval[1] = 0;
while (j < T.Length)
{
if (S.ch[i] == T.ch[j] || j == 0)//这里不讲究顺序,j等于0不必要写在前面
{
++i; ++j;
if (T.ch[i] != S.ch[j])
{
nextval[i] = j;
}
else
nextval[i] = nextval[j];
}
else j = nextval[j];
}
return OK;
}
Status KMP(SString S, SString T,int nexter[])
{
int i, j;
i = 1; j = 1;
while (j < T.Length && i < S.Length)
{
if (S.ch[i] == T.ch[j]||j==0)
{
i++;
j++;
}
else { j =nexter[j]; }
}
if (j >= T.Length)
printf("匹配成功!\n位置为:%d\n", i - j + 1);
else printf("匹配失败,不存在匹配\n");
return OK;
}
int main()
{
SString S, T;
int next[Sizemax],nextval[Sizemax];
InSString(S, T);
shuru(S, T);
Display(S, T);
Get_next(S,T,next);
KMP(S,T,next);
Get_nextval(S, T, nextval);
KMP(S, T, nextval);
}
KMP算法详细代码
最新推荐文章于 2024-07-10 16:47:58 发布