您的位置:首页 > 其它

LeetCode 28 Implement strStr()(子字符串查找)

2017-05-16 19:42 507 查看
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

题目大意:实现strStr(char* s, char* t)函数,该函数的作用是返回字符串t第一次出现在字符串s中的下标。

解题思路:懒得写KMP了(主要是忘了。。。),直接写了一个BF,结果发现貌似比讨论区的KMP还快,可能是数据比较水吧。

代码如下:

int strStr(char* haystack, char* needle) {
int h = strlen(haystack);
int n = strlen(needle);

for(int i = 0;i <= h - n;++i){
int j;
for(j = 0;j < n;j++){
if(haystack[i + j] != needle[j])
break;
}
if(j == n) return i;
}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode