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;
}

本文介绍了一个字符串查找函数strStr()的两种实现方式:一种是直接逐字符对比,另一种是在确定haystack剩余长度小于needle长度时提前终止搜索以提高效率。
182

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



