LeetCode Implement strStr()

本文深入探讨了KMP算法的原理与应用,通过实例代码展示了如何使用该算法解决字符串匹配问题。从理论到实践,逐步解析算法核心,提供调试经验分享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这题就是KMP算法,看了几遍还是没能想起来,又拿起书看了看,写了程序,bug不少,调了好久,通了。

char *strStr(char *haystack, char *needle) {
	if (haystack==NULL||needle==NULL)
	{
		return NULL;
	}
	int lenneedle=0;
	char *p=needle;
	while(*p)
	{
		p++;
		lenneedle++;
	}
	int *nextval = new int[lenneedle];
	nextval[0] = -1;
	int i=0,j=-1;
	while(i<lenneedle-1)//this is vital 
	{
		if (j==-1||needle[i]==needle[j])
		{
			++i;
			++j;
			if (needle[i]!=needle[j])
				nextval[i] = j;
			else
				nextval[i] = nextval[j];
		}
		else
			j = nextval[j];
	}
	int hi=0;
	int ni=0;
	while(*haystack&&ni<lenneedle)
	{
		if (ni==-1||*haystack==needle[ni])
		{
			haystack++;
			ni++;
		}
		else
			ni = nextval[ni];
	}
	delete[] nextval;
	if (ni>=lenneedle)
	{
		return haystack - lenneedle;
	}
	else
		return NULL;
}
char str1[20]="acabaabaabcacaabc";
	char str2[]="abaabcac";
	cout<<strStr(str1,str2)<<endl;
采用的是严蔚敏那本书上的程序和例子。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值