[C++]LeetCode 28: Implement strStr() (实现strStr()函数)

来源:互联网 发布:minix3源码在哪下载 编辑:程序博客网 时间:2024/05/06 21:20

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


0 0
原创粉丝点击