一眼kmp---字符串匹配算法嗷。
前缀串 后缀串 前缀表 最长相等前后缀串长度 --搞清楚概念
首先构建 next前缀表
传入needle查询的字符串构建next数组
细节就是 i表示后缀末尾位 j表示前缀末尾位置(最长前后缀相等长度)
j要从0开始嗷
然后就是while中表示回退的下标
最重要就是:j = next[j-1] 表示若是不匹配返回最初相等串的下标位置
next[i] = j; 表示 前缀表的值 是 j的值
查询函数中 查询字符串要从0开始匹配 最后返回下标即可。
class Solution {
public:
void getnext(int* next, const string& s){
int j = 0;
next[0] = 0;
for (int i = 1; i < s.size(); ++i){
while (j > 0 && s[i] != s[j]){
j = next[j - 1];
}
if (s[i] == s[j]){
++j;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) return 0;
int next[needle.size()];
getnext(next,needle);
int j = 0;
for (int i = 0; i < haystack.size(); ++i){
while (j > 0 && haystack[i] != needle[j]){
j = next[j-1];
}
if (haystack[i] == needle[j]) ++j;
if (j == needle.size()) return (i - needle.size() + 1);
}
return -1;
}
};