Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思路:暴力法或者KMP
代码:
暴力法:
char *strStr(char *haystack, char *needle) {
int lenOfHaystack=strlen(haystack);
int lenOfNeedle=strlen(needle);
if(lenOfHaystack<lenOfNeedle)
return NULL;
if(lenOfNeedle==0)
return haystack;
char *res=NULL;
char *p=haystack;
char *q=needle;
while(*p!='\0' && *q!='\0')
{
if(*p == *q)
{
if(res == NULL)
{
res=p;
}
++p;
++q;
}
else
{
if(res == NULL)
{
++p;
}
else
{
q=needle;
p=++res;
res=NULL;
}
}
}
if(res!=NULL && *q!='\0')
{
return NULL;
}
return res;
}