1刷
KMP经典算法,主要是了解KMP基本原理, next数组怎样求!
class Solution {
public:
int next[500001];
void makenext(string s){
int n = s.size();
next[0] = 0;
int k = 0;
for(int i = 1; i < n; ++ i){
while(k > 0 && s[k] != s[i])
k = next[k - 1];
if(s[k] == s[i]) k++;
next[i] = k;
}
}
int strStr(string haystack, string needle) {
int n = haystack.size();
int m = needle.size();
if(m == 0) return 0;
int num = -1;
makenext(needle);
for(int i = 0, j = 0; i < n; ++ i){
while(j > 0 && haystack[i] != needle[j])
j = next[j - 1];
if(haystack[i] == needle[j])
j++;
if(j == m){
num = i - m + 1;
break;
}
}
return num;
}
};
2刷
没啥好说的,就是kmp,要记住next数组是怎样求的,其实next的求法跟kmp匹配时候基本大同小异,就是容易忘记,背住那两幅next的图就ok比较好理解。
注意小细节ps
int n = needle.length();
if(n == 0) return 0
注意这个就ok,可以3刷
class Solution {
public:
vector<int>next;
void makenext(string s){
int n = s.length();
for(int i = 0; i < n; ++ i) next.push_back(0);
for(int i = 0, j = 1; j < n; ++ j){
while(i > 0 && s[i] != s[j]) i = next[i - 1];
if(s[i] == s[j]) i++;
next[j] = i;
}
}
int index = -1;
int strStr(string haystack, string needle) {
int m = haystack.length();
int n = needle.length();
if(n == 0) return 0;
makenext(needle);
for(int i = 0, j = 0; i < m; ++ i){
while(j > 0 && haystack[i] != needle[j]) j = next[j - 1];
if(haystack[i] == needle[j]) j++;
if(j == n){
index = i - n + 1;
break;
}
}
return index;
}
};