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;
}
本文介绍了如何使用C语言实现strStr()函数,该函数用于在haystack字符串中查找首次出现needle字符串的位置。文章提供了暴力匹配法的具体实现,并讨论了边界情况。
623

被折叠的 条评论
为什么被折叠?



