Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
char *strStr(char *haystack, char *needle) {
// Note: The Solution object is instantiated only once.
if(!*needle)return haystack;
while(*haystack != '\0')
{
if(*haystack == *needle)
{
char* h = haystack;
char* n = needle;
while(*h != '\0' && *n!= '\0' && *h==*n)h++,n++;
if(*n=='\0')
return haystack;
}
haystack++;
}
return NULL;
}
优化:当haystack后面的长度小于needle的长度时就不用再匹配了。
char *strStr(char *haystack, char *needle) {
// Note: The Solution object is instantiated only once.
if(!*needle)return haystack;
char* pend = haystack;
char* tmp = needle;
while(*++tmp)pend++;
while(*pend != '\0')
{
if(*haystack == *needle)
{
char* h = haystack;
char* n = needle;
while(*h != '\0' && *n!= '\0' && *h==*n)h++,n++;
if(*n=='\0')
return haystack;
}
haystack++;
pend++;
}
return NULL;
}