KMP模式匹配


1,若第i个开始不等,移动到第i个。

直接将sub[0]与src[5]比较。

012345678
abcababca
abcabx   

 

2,

sub[2]与src[5]比较。

012345678
abcababca
   abcab 

 

看大神的代码理解不了,还是按自己的思路写一个,繁琐还是起码好理解就行。

 

 

void getNext(const char * sub, int next[])
{
	int i=1,compareIndex=0;	
	next[0]=-1;
	next[1]=0;
	bool bLastEquel=false;
	while (sub[i+1]!='\0')
	{
		
		if(sub[i]==sub[compareIndex])
		{
			bLastEquel=true;
			i++;
			compareIndex++;
			// original_next=compareIndex
			if(sub[i]==sub[compareIndex]) //判断当前的sub[i]字符与originalNext对应sub字符是否相等
				next[i]=next[compareIndex];
			else
				next[i]=compareIndex;
		}
		else
		{
			compareIndex=0;
			if (bLastEquel==false)
			{
				i++;
				if(sub[i]==sub[compareIndex])
					next[i]=next[compareIndex];
				else
					next[i]=compareIndex;
			}
			bLastEquel=false;
		}
	}

}

int strstrForNext(const char *src,const char *sub)
{
	assert(src!=nullptr&&sub!=nullptr);
	const char* src2=src,*sub2=sub;
	size_t index=0;
	int *pNext = new int [strlen(src)];
	get_nextval(sub,pNext);

	size_t i=0,j=0;
	while (  src2[i]=='\0' && sub2[j]=='\0' )
	{

		if (src2[i]==sub2[j])
		{
			i++;
			j++;
		}
		else
		{
			index=index+j+1;
			if(pNext[j]==-1)
			{
				i++;
				j=0;
			}
			else
				j=pNext[j];

		}		
	}
	delete []pNext;
	if ( sub2[j]=='\0')
	{
		return index;
	}
	return -1;
}



int main()
{
	char *p="aaaaaaaab";
	char *q="yu";
	int *nextRes=new int[strlen(p)+1];

	getNext(p,nextRes);	

	for (int i=0;i<strlen(p)+1;i++)
	{
		cout<<nextRes[i]<<endl;
	}
	cout<<strstrForNext(p,q)<<endl;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值