Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
实现 strStr().返回字串在字符串中第一次出现的位置,不存在则返回-1.
分析:
逐个字符比较,当字符串中剩下未被检索的字符串长度小于字串长度时就可停止检索。也可以使用 KMP 算法。
int strStr(char* haystack, char* needle) {
char *pstartHay = haystack, *pt = NULL;
char *pneedle = needle;
int haylen = 0, needlen = 0;
if(!haystack || !needle)/*空指针*/
return -1;
haylen = strlen(haystack);
needlen = strlen(needle);
if(haylen < needlen)/*待找字符串长度大于被找字符串*/
{
return -1;
}
while((haystack + haylen - pstartHay) >= needlen) /*还未匹配的字符串要大于待匹配字符串*/
{
pt = pstartHay;
pneedle = needle;
while(*pneedle)
{
if(*pt != *pneedle) /*存在不匹配字符,不再比较*/
break;
++pt;
++pneedle;
}
if(!*pneedle) /*完全匹配*/
{
return (pstartHay - haystack);
}
++pstartHay;
}
return -1;
}
本文介绍了如何用C语言实现LeetCode上的Implement strStr()问题,该函数旨在找到字串在字符串中首次出现的位置,若未找到则返回-1。解析中提到可以逐个字符比较,或者应用KMP算法来提高效率。
1104

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



