题目描述:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1: 输入: haystack = "hello", needle = "ll" 输出: 2
示例 2: 输入: haystack = "aaaaa", needle = "bba" 输出: -1
这道题我在自己做的时候,使用了“自以为是”的“双指针”方法,等到浅显的了解了下KMP算法后,发现我的所谓双指针算法只是表面上的,实际上还是里外两次遍历,具有很高的时间复杂度。这里直接上原来的代码,就不多做解释了。
int strStr(string haystack, string needle) {
int slow = 0, fast = 0;
int len = needle.length();if (needle.length() > haystack.length()) return -1;
while (slow <= haystack.length() - len)
{
if (haystack[slow] != needle[0])
{
slow++;
fast++;
}
else {
int count = 0;
int f = fast;
for (fast; fast < f + len; fast++)
{
if (haystack[fast] == needle[count])
count++;
}
if (count == len)
return slow;slow++