//第一,请实现KMP算法;
//第二,考虑KMP算法的优化,以模式串为aaaaaaaaaaab为例
//第一,请实现KMP算法;
//第二,考虑KMP算法的优化,以模式串为aaaaaaaaaaab为例
#include <iostream>
#include <string>
using namespace std;
#define MAXSTRLEN 255//用户可在255以内定义最大串长
typedef struct {
char ch[MAXSTRLEN];
int length;
}SString;
bool StrAssign(SString& T, char* chars) {
//生成一个其值等于串常量chars的串T
int i = 1;
while (chars[i - 1] && i < 255) {
T.ch[i] = chars[i - 1];
i++;
}
if (i == 255 && chars[i]) {
return 0;
}
T.length = i - 1;
return true;
}
void get_next(SString T, int next[]) {
int i = 1, j= 0;
next[1] = 0;
while (i < T.length) {
if (j == 0 || T.ch[i] == T.ch[i]) {
i++;
j++;
next[i] = j;
}
else {
j = next[j];
}
}
}
void get_nextval(SString T, int next[]) {
int i, m;//i为字符串下标,m为最大相同前后缀大小
next[0] = 0;
for (i = 1, m = 0;i < T.length;i++)
{
if (T.ch[i] == T.ch[m])
next[i] = next[m];
else
next[i] = m;
while (m > 0 && T.ch[i] != T.ch[m])
{
m = next[m - 1];
}
if (T.ch[i] == T.ch[m])
{
m++;
}
}
}
int Index_KMP(SString S, SString T) {
int i = 1;
int j = 1;
int* next = new int(T.length + 1);
get_next(T, next);
while (i <= S.length && j <= T.length) {
if (j == 0 || S.ch[i] == T.ch[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
delete next;
if (j > T.length) {
return i - j + 1;
}
else {
return 0;
}
}
int Index_KMPval(SString S, SString T) {
int i = 1;
int j = 1;
int* next = new int(T.length + 1);
get_nextval(T, next);
while (i <= S.length && j <= T.length) {
if (j == 0 || S.ch[i] == T.ch[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
delete next;
if (j > T.length) {
return i - j + 1;
}
else {
return 0;
}
}
int main() {
char s1[255] = "aaaaaaaaaaab";
char s2[255] = "aaaab";
SString S1, S2;
StrAssign(S1, s1);
StrAssign(S2, s2);
cout <<"优化前:"<< Index_KMP(S1, S2);
cout << "优化后:" << Index_KMPval(S1, S2);
return 0;
}