c语言解释KMP算法

介绍

KMP算法是解决字符串匹配问题的一种优化算法,时间复杂度为线性的O(m+n)。

应用场景

给定一个字符串string和模式串compile,求解模式串compile在字符串string中的位置

方法一:暴力匹配

如果选用暴力匹配,并假设字符串中匹配到 i 位置,模式串中匹配到 j 位置,则:

  • 如果当前字符匹配成功,即string[i]==compile[j],则 i 和 j 自增,继续匹配下一个字符。
  • 如果当前字符匹配失败,即string[i]!=compile[j],则i回到原来位置的后一位,j重置到模式串的头部,即i=i-j+1,j=0。
void index_force(char* string, char compile[]) {
	int i = 0;
	int j = 0;
	while (i < strlen(string) && j < strlen(compile)) {
		if (string[i] == compile[j])
		{
			i++;
			j++;
		}
		else
		{
			i -= j - 1;
			j = 0;
		}
	}
	if (j == strlen(compile)) printf("下标为%d", i-j);
	else printf("未匹配到数据");
}

方法二:KMP算法

  • 求得next数组,可以使用数学推理或者最长相等前后缀来理解
void get_next(char* compile, int next[]) {
	next[0] = -1;
	int i = 0;
	int j = -1;
	while (i < strlen(compile)) {
		if (j==-1||compile[i] == compile[j]) {
			i++;
			j++;
			if (compile[i] != compile[j])
				next[i] = j;
			else
                //对next数组进行优化
				next[i] = next[j];
		}
		else
			j = next[j];
	}
}
  • 进行匹配
void index_KMP(char* string, char compile[],int pos) {
	int i = pos;
	int j = 0;
	int next[9] = {};
	get_next(compile, next);
	while (i<strlen(string) && j<strlen(compile))
	{
		if (compile[j] == string[i]) {
			i++;
			j++;
		}
		else {
			next[j] == -1 ? i++, j=0 :j=next[j] ;
		}
	}
	if (j == strlen(compile))
		printf("下标为%d", i - strlen(compile));
	else
		printf("未找到");
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

辰宝IWZ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值