c语言实现KMP算法

KMP算法

1.主串的i不回退
2.字串的j不会每次回退到字串开始处
int KMP(char* str, char* sub, int pos)
{
	assert(str && sub);
	int StrLen = strlen(str);
	int SubLen = strlen(sub);
	assert(StrLen >= SubLen);
	assert(pos >= 0 && pos < StrLen);

	int* next = (int*)malloc(sizeof(int) * SubLen);
	GetNext(sub, SubLen, next);
	int* nextval = (int*)malloc(sizeof(int) * SubLen);
	GetNextVal(sub, SubLen, next, nextval);
	
	int i = pos;
	int j = 0;
	while (i < StrLen)
	{
		if (j == -1 || str[i] == sub[j];
		{
			i++;
			j++;
		}
		else
		{
			j = nextval[j];//回退到j要回退的位置,即该位置之前有两个相等字串,不需要比较
		}
	}

	if (j >= SubLen)
		return i - j;
	return -1;
}
	

next数组

针对字串每次不回退到开始处,创建next原来保存j每次回退的位置。next数组的0下标值为-1,1下标值为0,固定不变。next值表示字串中,以0下标的字符为开头,以j-1下标为结尾的两个相等字串的长度,如果没有相等字串,next值为0。

1.next的值递增规律总是+1,每增加一个字符,相等字符串的字符数最多+1,但能直接减少为0
2.字串的最后一个字符不影响next数组的值。
void GetNext(char* sub, int SubLen, int* next)
{
	next[0] = -1;
	next[1] = 0;

	int i = 2;
	int k = 0;//k为sub[i-1]的next值,前一项要回退到的下标
	while (i < SubLen)
	{
		if (k == -1 || sub[i -1] =sub[k])
		{
			next[i] = k + 1;
			i++;
			k++;
		}
		else
		{
			k = next[k];
		}
	}
}

nextval

当遇到一个字符发生回退时,如果回退的字符与回退之前的字符一样,则该字符的nextval值保存为回退字符的next值。如果不相同则保存.

回退的字符与没回退之前一样,回退便无意义,所以要回退到与没回退之前的字符不一样的字符处。

void GetNextVal(char* sub, int SubLen, int* next, int* nextval)
{
	nextval[0] = -1;

	for (int i = 1; i < SubLen; i++)
	{
		if (sub[i] == sub[next[i]])
			nextval[i] = next[next[i]];
		else
			nextval[i] = next[i];
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值