admin管理员组文章数量:1636959
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;
}
本文标签: 函数LeetCodestrStrimplement
版权声明:本文标题:[C++]LeetCode 28: Implement strStr() (实现strStr()函数) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1729234482a1191837.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论