#include <iostream>
#include <string>
using namespace std;
namespace KMP {
auto next(char T[],int* next) -> void {//它在比较字符时也是用的KMP算法思想
next[0] = -1;
int lenT = strlen(T);
int i = 0;//后缀
int j = -1;//前缀 相当于KMP算法中的模式串的指针
while (i < lenT) {//i遍历完这个串就退出
if (j == -1 ||T[j] == T[i]) {
j++;
i++;
next[i] = j;//可能于这段代码有关系因为如果我在这个函数开辟int数组它会说next的范围是0到0
}
else {
j = next[j];//失败的时候还是回退到next[j]的位置
}
}
}
auto KMP(char S[], char T[]) -> int {
int i = 0;
int j = 0;
int lenS = strlen(S);
int lenT = strlen(T);
int* next = new int[lenT];
KMP::next(T, next);
while (i < lenS && j < lenT) {
if (S[i] == T[j]) {//匹配相等的话 主串和字串都向下移动一个单位
i++;
j++;
}
else {
j=next[j];
if (j == -1) {
i++;
j++;
}
}
}
delete[] next;//这里不允许释放 这里注释了就没有问题
if (j == lenT) {//这里如果是子串退出就说明找到了 不能用主串退出,因为主串退出也有可能是没找到
return i - j;
}
return -1;
}
}
int main()
{
char S[5] = { 'a','b','c','e','\0'};
char T[5] = { 'a','b','c','e','\0'};
cout << KMP::KMP(S, T) << endl;
}
问题描述在注释里 ,麻烦同志们帮我解决一下 谢谢
补充:用vs2022的release就没有问题用debug就有问题