28. Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1


思路:这是一个字符串匹配的题,暴力求解的话,复杂度这里是可以通过的。我们先用暴力求解。再用稍微麻烦点的但是效率高的KMP算法。

暴力法:(O(m*n))
int strStr(string haystack, string needle) {
        	int n1=haystack.size();
	int n2=needle.size();
    if(n2==0)
        return 0;
	if(n1==0||n2>n1)
		return -1;
	int index=0;
	int start=0;
	int j=0;
	int i=0;
	while(i<n1)
	{
		index=start;
		while(i<n1&&j<n2&&haystack[i]==needle[j])
		{
			i++;
			j++;
		}
		if(j==n2)
			return index;
		start++;
		i=start;
		j=0;
	}
	return -1;
	
    }

KMP算法(在算法专题学习中,有详细介绍,不赘述):O(m+n)
void makeNext(int next[],string P)
{
	int q,k;
	int m=P.size();
	next[0]=0;
	for(q=1,k=0;q<m;q++)
	{
		while(k>0&&P[q]!=P[k])
			k=next[k-1];
		if(P[k]==P[q])
			k++;
		next[q]=k;
	}

}
int KMP( string P,string T,int next[])
{
	int m=P.size();
	int n=T.size();
	makeNext(next,P);
	for(int i=0,q=0;i<n;i++)
	{
		while(q>0&&T[i]!=P[q])
		{
			q=next[q-1];
		}
		if(T[i]==P[q])
			q++;
		if(q==m)
			return i+1-m;
	}
}
int strStr(string haystack, string needle) 
{
	int next[20]={0};
	
	return KMP(needle,haystack,next);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值