C语言 实现 KMP算法

 

 

已传入github,可下载,想测试对应函数,调用传参即可,记得注释掉之前的主函数

文件名为2022_1_19,因为是是那天写的

GitHub - frankRenlf/c_programsicon-default.png?t=M0H8https://github.com/frankRenlf/c_programs.git部分代码如下:

我使用了两种方法写KMP算法,前一种参考了网上其他人的写法,不过重点在后面mykmp函数上,

个人认为用动态内存的方法更好,节省空间,并优化了计算速度.

其中nextval可以节省大量运行时间,极大提升函数在面对某些cases的运行速度.你们可以好好想想怎么提升的.

void Next(char* T, int* next) {
	int i = 1;
	next[1] = 0;
	int j = 0;
	while (i < strlen(T)) {
		if (j == 0 || T[i - 1] == T[j - 1]) {
			i++;
			j++;
			next[i] = j;
		}
		else {
			j = next[j];
		}
	}
}
int KMP(char* S, char* T) {
	int next[10];
	Next(T, next);//根据模式串T,初始化next数组
	int i = 1;
	int j = 1;
	while (i <= strlen(S) && j <= strlen(T)) {
		//j==0:代表模式串的第一个字符就和当前测试的字符不相等;
		//S[i-1]==T[j-1],如果对应位置字符相等,两种情况下,指向当前测试的两个指针下标i和j都向后移
		if (j == 0 || S[i - 1] == T[j - 1]) {
			i++;
			j++;
		}
		else {
			j = next[j];//如果测试的两个字符不相等,i不动,j变为当前测试字符串的next值
		}
	}
	if (j > strlen(T)) {//如果条件为真,说明匹配成功
		return i - j;
	}
	return -1;
}

void myNext(const char* sub, int* next, int len_sub)
{
	next[0] = -1;
	if (len_sub == 1)
	{
		return;
	}
	next[1] = 0;
	int i = 2;
	int k = 0;
	while(i < len_sub)
	{
		if (k == -1 || sub[i - 1] == sub[k])
		{
			next[i] = k + 1; 
			i++;
			k++;
		}
		else
		{
			k = next[k];
		}
	}
}

void myNextval(const char* sub, int* nextval, int* next, int len_sub)
{
	nextval[0] = next[0];
	for (int i = 1; i < len_sub; i++)
	{
		if (sub[i] == sub[next[i]])
		{
			nextval[i] = nextval[next[i]];
		}
		else
		{
			nextval[i] = next[i];
		}
	}
}

int myKMP(const char* str, const char* sub, int pos)
{
	assert(str && sub);
	int len_str = strlen(str);
	int len_sub = strlen(sub);
	if (len_str == 0 || len_sub == 0)
	{
		return -1;
	}
	if (pos<0 || pos>len_str)
	{
		return -1;
	}
	
	int* next = (int*)malloc(sizeof(int) * len_sub);
	int* nextval = (int*)malloc(sizeof(int) * len_sub);
	assert(next && nextval);
	myNext(sub, next, len_sub);
	myNextval(sub, nextval, next, len_sub);

	int i = pos;
	int j = 0;
	
	while (i < len_str && j < len_sub)
	{
		if (j == -1 || str[i] == sub[j])
		{
			i++;
			j++;
		}
		else
		{
			j = nextval[j];
		}
	}
	free(next);
	free(nextval);
	if (j >= len_sub)
	{
		return i - j;
	}
	else
	{
		return -1;
	}
}

有问题可在评论指出,觉得还行就给个赞和关注吧

也可以关注这个系列,后续也会有更新,和其他代码产出

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Frank.Ren

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

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

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

打赏作者

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

抵扣说明:

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

余额充值