typedef struct {
char str[MAX];
int length;
}SString;
BF算法
int Index(SString *S, SString *T)
{
int i, j;
i = 1; j = 1;
while (i<=S->length&&j<=T->length)
{
if (S->str[i] == T->str[j])
{
i++;
j++;
}
else
{
i = i - j + 2;
j = 1;
}
}
if (j > T->length)
return i - T->length;
else
return 0;
}
KMP算法
int Index_KMP(SString *S, SString *T,int *next)
{
int i = 1, j = 1;
while (i <= S->length && j <= T->length)
{
if (j == 0 || S->str[i] == T->str[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j > T->length)
return i - T->length;
else
return 0;
}
求next数组
void get_next(SString* S, int *&next)
{
next=(int *)malloc(sizeof(int)*S->length);
int i = 1, j = 0;
next[1] = 0;
while (i <= S->length)
{
if (j == 0 || S->str[i] == S->str[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
求nextval数组
void get_nextval(SString*T,int *&nextval)
{
nextval=(int *)malloc(sizeof(int)*T->length);
int i = 1, j = 0;
nextval[1]=0;
while(i<=T->length)
{
if(j==0||T->str[i]==T->str[j])
{
i++;j++;
if(T->str[i]!=T->str[j])
nextval[i]=j;
else
nextval[i]=nextval[j];
}
else
j=nextval[j];
}
}
原文:https://www.cnblogs.com/KIROsola/p/12088491.html