一.题目
二.解法
1.KMP算法
int strStr(char* haystack, char* needle) {
int M = strlen(haystack);
int N = strlen(needle);
int next[N];
getnext(next,needle);
int i=0,j=0;
while(i<M&&j<N)
{
if(haystack[i]==needle[j])
{
i++;
j++;
}
else if(j==0)
i++;
else
j = next[j];
}
return j == N ? i-N:-1;
}
void getnext(int *next,char *p)
{
int i=2,j=0;
int N = strlen(p);
if(N==1)
next[0] = -1;
else
{
next[0] = -1;
next[1] = 0;
while(i<N)
{
if(p[i-1]==p[j])
next[i++]=++j;
else if(j>0)
j = next[j];
else
next[i++] = 0;
}
}
}
2.strnmp函数
int strStr(char* haystack, char* needle) {
int i;
for(i=0;i<strlen(haystack);i++)
{
if(strncmp(haystack+i,needle,strlen(needle))==0)
return i;
}
return -1;
}