KMP算法详细代码

#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);
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桂亭亭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值