实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
示例 2:
输入:haystack = "aaaaa", needle = "bba"
输出:-1
示例 3:
输入:haystack = "", needle = ""
输出:0
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的理解:
这道题在我们学习数据结构的字符串的时候,已经研究过了,他有两种比较普遍的算法,BF算法和KMP算法,BF算法很简单,而KMP算法很难理解,当然了算法的时间复杂度也不同。
BF算法代码段:
int strStr(const char* haystack,const char* needle)
{
if(needle==NULL)
{
return 0;
}
int len1 = strlen(haystack);
int len2 = strlen(needle);
int i = 0,j = 0;
while (i < len1 && j < len2)
{
if (haystack[i] == needle[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == len2)
return i -j;
else
return -1;
}
这个算法很好理解,多的不说了。
KMP算法代码段:
void Getnext(int next[], const char* needle)
{
int k = -1, i = 0;
next[0] = -1;
int len = strlen(needle);
while (i < len - 1)
{
if (k == -1 || needle[k] == needle[i])
{
k++;
i++;
next[i] = k;
}
else
{
k = next[k];
}
}
}
int strStr(const char* haystack,const char* needle)
{
if(needle==NULL)
{
return 0;
}
int len1 = strlen(haystack);
int len2 = strlen(needle);
int next[100];
Getnext(next, needle);
int i = 0, j = 0;
while ((i < len1) && (j < len2))
{
if (j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j == len2)
{
return i - len2;
}
return -1;
}
这个真的是难以理解,我理解了好几天,才看明白,大家直接在网上找一些大牛写的vlod比较好。