题目链接:https://leetcode.com/problems/implement-strstr/
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
int strStr(char* haystack, char* needle) {
if(*needle == '\0')
return 0;
int index = 0;
int len1 = strlen(haystack), len2 = strlen(needle);
while(index <= len1 - len2) { //母串剩余字符数小于字串时不需要继续遍历;当字串较大时可以节约很多时间
int i = 0; //从第一个字符开始比较,直到出现不相同字符
while(haystack[index + i] && needle[i] && haystack[index+i] == needle[i])
++i;
if(needle[i] == '\0') //找到相同字串则返回
return index;
++index;
}
return -1; //不包含字串则返回-1
}