kmp字符串匹配代码问题
程序代码:#include <iostream>
#include <string.h>
using namespace std;
//kmp算法的next函数下标从0开始
void next(const char *szMsg, int next1[])
{
int j = 0;
int k = -1;
next1[0] = -1;
while(j<strlen(szMsg)-1)//次数,以下的需要画图理解
{
if (k == -1||szMsg[j] == szMsg[k])//字符匹配
{
++j;
++k;
if (szMsg[j] != szMsg[k]) //
next1[j] = k;//
else//相等就是说有重复的字符
next1[j] = next1[k];
}
else
{
k = next1[k];//k返回到next(k)
}
}
return;
}
int Index(const char *szMsg, const char* str)
{
int lenszMsg=strlen(szMsg);
int len = strlen(str);
int *next1 = new int[len];
next(szMsg, next1);//next函数
int i = 0;
int j = 0;
while(i < lenszMsg&& j<len)
{
if (j ==-1||szMsg[i] == str[j])//字符匹配
{
i++;//往下匹配
j++;
}
else
j = next1[j];//不匹配往回找,i不变
}
if (j==len)
return i-len;//匹配返回从第几个下标开始匹配
return -1;//不匹配
}
int main()
{
char szMsg[256];
char str[256];
cout << "输入目标串:" ;
cin >> szMsg;
cout << "输入子串:";
cin >> str;
int len =strlen(szMsg);
if (Index(szMsg,str)!=-1)
cout << "在 " << szMsg << " 中可以找到 " << str <<endl;
else
cout << "在 " << szMsg << " 中找不到 " << str <<endl;
return 0;
}
输入的字符串小一点有没有错误。我调不出来原因







