leetcode上的一道题:https://oj.leetcode.com/problems/implement-strstr/
实际上就是实现KMP算法,但是该算法我觉得算法导论讲的过于精简,理论证明过多导致初学者不容易搞懂,所以特别打印了csdn 人气博主 July(周磊)新书初稿KMP算法部分学习,发现他说的更加通熟易懂,而且是以例子来进行教学,比较容易接受。PDF下载地址:http://download.csdn.net/detail/huruzun/7819137
引用PDF中主体代码:
class Solution
{
public:
int getlen(char *str)
{
int i;
for(i = 0; str[i] != '\0'; i ++)
;
return i;
}
void getnext(char *str, int len, int next[])
{
int i = 0;
next[i] = -1;
int j = -1;
while(i < len-1)
{
if(j==-1 || str[i]==str[j])
{
i++;
j++;
if(str[i] == str[j])
next[i] = next[j];
else
next[i] = j;
}
else
j = next[j];
}
}
char *strStr(char *haystack, char *needle)
{
int hlen = getlen(haystack);
int nlen = getlen(needle);
int *next = new int[nlen];
getnext(needle, nlen, next);
int i = 0;
int j = 0;
while(i != hlen && j != nlen)
{
if(j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if(j == nlen)
return &haystack[i-nlen];
else
return NULL;
}
};