class KMP{
string pattern;
int len ;
vector next; // 这里的next数组是从1开始的
// 也叫失配数组,next[i] 表示以第i位结尾的子串与模式串的前缀相同的最大长度(但不能是自身),也就是所谓的最长公共前后缀
void Next(){
next.resize(len+1);
int j = 0;
for(int i = 2; i <= len; i++) {
while(j > 0 && pattern[i] != pattern[j + 1]) {
j = next[j];
}
if(pattern[i] == pattern[j + 1]) {
j++;
}
next[i] = j;
}
}
public:
KMP(const string &pattern) {
len = pattern.size();
this->pattern = " " + pattern;
Next();
}
bool isSubstringOfText(const string& text) {
return getPositions(text).size() > 0;
}
// 统计模式串在文本串出现的次数
int getTimes(const string& text) {
return getPositions(text).size();
}
// 统计模式串在文本串的出现的次数
vector getPositions(const string& text) {
vector res;
if(text.size() < len) return res;
int j = 0;
for(int i = 0; i < text.size(); i++){
while (j > 0 && text[i] != pattern[j + 1]){
j = next[j];
}
if(text[i] == pattern[j + 1]){
j++;
}
if(j == len){
// i 是匹配时文本串的位置(从0开始)
res.push_back(i);
j = next[j];
}
}
re 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 turn res;
};
// 求数组f[] 其中 f[i] 表示文本串以i结尾的子串与 pattern 串的前缀相同的最大长度(这里也是从1开始计数)
vector getFArray(const string& text) {
int m = text.size(), j = 0;
vector f(m+1);