一句话总结:空间换时间,用一个next数组保存不匹配时下一次开始比较时两个字符串指针的位置;next[ i ]中保存的是前i个字符后缀与前缀相同的个数。
参考资料:
【1】一个将KMP的视频,很好理解,而且很短,只有十来分钟。
https://www.bilibili.com/video/av3246487?from=search&seid=18035591679131870458
【2】博客
https://www.cnblogs.com/zzzdp/p/9416570.html
https://www.nowcoder.com/discuss/4236?type=0&order=0&pos=309&page=0?from=wb
练习题:leetcode 28 Implement strStr()
class Solution {
public:
/* 暴力运算 4ms 9MB*/
/*
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
for(int i = 0; i <= m-n; i ++)
{
int j;
for(j = 0; j < n; j ++)
{
if(haystack[i+j] != needle[j])
break;
}
if(j == n)
return i;
}
return -1;
}
*/
/* KMP */
void get_next(string str, vector<int> &next){
int i = 0;
int j = 1;
while(j < str.size()){
while(i > 0 && str[i] != str[j])
{
i = next[i - 1];
}
if(str[i] == str[j]){
next[j] = i + 1;
j++;
i++;
}
else {
j++;
}
}
}
int get_str(string text, string pattern) {
int m = text.size();
int n = pattern.size();
vector<int> next(n, 0);
get_next(pattern, next);
int i = 0;
int j = 0;
while(i < m){
while(j > 0 && text[i] != pattern[j]){ // 找到pattern开始比较的字符
j = next[j - 1];
}
if(text[i] == pattern[j]){
j++;
i++;
if(j == n){
return i - n;
}
}
else{ // 此时pattern的j == 0,并且text[i] != pattern[j],因此i自增
i++;
}
}
return -1;
}
int strStr(string haystack, string needle) {
if(needle.size() == 0){
return 0;
}
return get_str(haystack, needle);
}
};