#28 Implement strStr()

题目链接: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 theindexinstead of the pointer. If you still see your function signature returns achar *orString, please click the reload buttonto 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}

版权声明:本文为博主原创文章,未经博主允许不得转载。

当你感到悲哀痛苦时,最好是去学些什么东西。

#28 Implement strStr()

相关文章:

你感兴趣的文章:

标签云: