Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
本题为字符串匹配问题,在此次个人使用的BF方法,若优化使用KMP算法!详见
BF与KMP算法
char *strStr(char *haystack, char *needle) {
int len_haystack = strlen(haystack);
int len_needle = strlen(needle);
int count = 0;
int i = 0;
if(needle[0] == '\0')
return haystack;
for(; i < len_haystack && needle[count] != '\0';i ++)
{
if(haystack[i] == needle[count])
{
count ++ ;
}
else
{
i = i - count ;
count = 0;
}
}
if(needle[count] == '\0')
return haystack+i-count;
return NULL;
}
第二次
char *strStr(char *haystack, char *needle)
{
if(haystack == NULL ||needle == NULL) return NULL;
int count = 0 ;
char * needle_store = needle;
while(*haystack != '\0' && *needle != '\0')
{
if(*haystack == *needle)
{
haystack++;
needle++;
count++;
}
else
{
haystack -= count-1;
needle = needle_store;
count = 0;
}
}
if(*needle == '\0')
{
return haystack -= count;
}
else
{
return NULL;
}
}