Problem:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
分析:
int strStr(char* haystack, char* needle) 的作用是寻找needle在haystack中第一次出现的位置,若不存在则返回-1。
strStr()的详细介绍:cplusplus介绍,百度百科词条。
这个问题让我想到了KMP算法,但运行时间只是居中,后来索性用最简单的C编写,时间还是让人惊喜的。下次有更好的题目再讲解 以下KMP算法。
AC Code(C):
//72 / 72 test cases passed.
//Runtime: 0 ms
int strStr(char* haystack, char* needle) {
if (haystack == NULL || needle == NULL) {
return -1;
}
if (*needle == '\0') {
return 0;
}
int needLength = (int)strlen(needle);
int hayLength = (int)strlen(haystack);
if (hayLength < needLength) {
return -1;
}
for (int i = 0; i < hayLength - needLength + 1; ++i) {
if (strncmp(haystack + i, needle, needLength) == 0) {
return i;
}
}
return -1;
}