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