您的位置:首页 > 其它

KMP —— next数组

2017-02-14 18:15 197 查看

求KMP算法中next数组



代码如下

#include "iostream"
#include <cstring>
using namespace std;
typedef char* String;

void Get_Next(String T, int *next)
{
int j, k;
j = 0;
k = -1;
next[0] = -1;
while(j < strlen(T))
{
if(k == -1 || T[j] == T[k])
{
j++;
k++;
next[j] = k;
}
else
{
k = next[k];
}
}
}

void main()
{
cout << "/** 说明:next就是输入的那一串字符每一个字符多对应的下标 ***/" << endl;
int N;
cout << "请输入你想测试的次数:" << endl;
cin >> N;
while (N--)
{
cout << endl;
cout << "请输入一串字符:" << endl;
char str[255];
cin >> str;
int next[255];
int i = 1;
//cout << strlen(str) << endl;
Get_Next(str, next);
cout << "每一个字符对应的next的值为:" << endl;
for (i = 0; i < strlen(str); i++)
{
printf("%d ", next[i]);
}
}
cout << endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kmp