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;
}
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);
}