字符串匹配(KMP算法)

int* Get_Next(const char* sub)
{
	assert(NULL != sub);
	int len = strlen(sub);
	int* next = (int*)malloc(len * sizeof(int));
	if (NULL == next)exit(1);
	//1.前两个格子给-1 0
	next[0] = -1;
	next[1] = 0;
	//2.通过已知推未知
	int j = 1;//j表示next数组的下标
	int k = next[1];//保存当前的回退位置,k在变化
	while (j + 1 < len)
	{
		if (k==-1||sub[j] == sub[k])
		{
			k++;
			j++;
			next[j] = k;
		}
		else
		{
			k = next[k];
		}
	}
	return next;
}
int KMP_Maching(const char* str, const char* sub)
{
	assert(str != NULL);
	assert(sub != NULL);
	int i = 0;
	int j = 0;
	int len_str = strlen(str);
	int len_sub = strlen(sub);
	int* next = Get_Next(sub);
	while (i <len_str && j < len_sub) 
	{
		if (j==-1||str[i] == sub[j]) 
		{
			i++;
			j++;
		}
		else
		{
			//让j回退到合适的位置,从而让i可以不用回退
			j = next[j];
		}
	}
	if (j > strlen(sub))
	{
		return -1;
	}
	free(next);
	return i - j;
}

int* Get_NextVal(const char* sub)
{
	int* next = Get_Next(sub);
	int len = strlen(sub);
	int* nextval = (int*)malloc(len * sizeof(int));
	if (NULL == nextval)exit(1);
	nextval[0] = -1;
	for (int i = 1; i < len; i++)
	{
		if (sub[i] == sub[next[i]])
		{
			nextval[i] = next[i];
		}
		else
		{
			nextval[i] = nextval[next[i]];
		}
	}
	free(next);
	return nextval;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值