【问题描述】
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
实现strstr(). 返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回nullptr。
注:strstr()是c++中的一个函数
【暴力破解】
时间复杂度O(N*M), 空间复杂度 O(1)
#include<iostream>
using namespace std;
// Returns a pointer to the first occurrence of needle in haystack,
// or null if needle is not part of haystack.
char *strStr(const char *haystack, const char *needle)
{
if (!*needle) return (char*)haystack;
const char *p1;
const char *p2;
const char *p1_advance = haystack;
for (p2 = &needle[1]; *p2; p2++)
p1_advance++;
for (p1 = haystack; *p1_advance; p1_advance++)
{
char *p1_old = (char *)p1;
p2 = needle;
while (*p1 && *p2 && *p1 == *p2)
{
p1++;
p2++;
}
if (!*p2) return p1_old;
p1 = p1_old +1;
}
return NULL;
}
void main()
{
char *haystack = "This a world!";
char *needle = "world";
int n = strStr(haystack, needle) - haystack;
cout << "The place is :" << n << endl;
}
其实这段代码自己不熟悉的一个是空指针的判断 if (!*p2)
【KMP】
// 待完成