题目
KMP
KMP就是要求最长相等前后缀:找到模式串的最长相等前后缀。(next或prefix数组)
理论:KMP
代码(7.31 首刷看解析)
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size(), n = needle.size();
// getnext
vector<int> need(n);
for(int i = 0, j = 1; j < n; j++) {
while(i > 0 && needle[i] != needle[j]) { // i要保证大于0,因为下面有取i-1作为数组下标的操作
i = need[i-1]; // 注意这里,是要找前一位的对应的回退位置了
}
if(needle[j] == needle[i]) // 如果匹配成功,往后移一格
i++;
need[j] = i;
}
int j = 0;
for(int i = 0; i < m; i++) {
while(j > 0 && haystack[i] != needle[j]) {
j = need[j-1];
}
if(haystack[i] == needle[j])
j++;
if(j == n)
return (i - n + 1);
}
return -1;
}
};
代码(9.21 二刷看解析)
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size(), n = needle.size();
vector<int> next(n);
getNext(next, needle);
for(int i = 0, j = 0; i < m; i++) {
while(j > 0 && needle[j] != haystack[i])
j = next[j-1];
if(needle[j] == haystack[i])
j++;
if(j == n)
return i-n+1;
}
return -1;
}
void getNext(vector<int>& next, string& needle) {
for(int i = 1, j = 0; i < needle.size(); i++) {
while(j > 0 && needle[i] != needle[j])
j = next[j-1];
if(needle[i] == needle[j])
j++;
next[i] = j;
}
}
};