主题:关于KMP算法
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define MAX 80
typedef struct string{
int length;
char s[MAX];
}*string;
creat()
{
string s;
s=(struct string *)malloc(sizeof(string));
gets(s->s);
s->length=strlen(s->s);
return s;
}
void get_next(string T)
{
int *next[MAX];
int i=1,j=0;
next[1]=(int*)malloc(sizeof(int));
*next[1]=0;
while(i<(T->length)){
if(j==0||(T->s[i]==T->s[j])){
i++;j++;
next[i]=(int *)malloc(sizeof(int));
*next[i]=j;
}
else j=*next[j];
}
}
int KMP(string S,string T)
{
int pos,i,j;
get_next(T);
i=pos;j=1;
while(i<=S->s[0]&&j<=T->s[0]){
if(j==0||S->s[i]==T->s[j]){
i++;j++;
}
else j= *next[j];
}
if(j>(T->length)) return (i-(T->length));
else return 0;
}
main()
{
int n;
string S,T;
S=(struct string *)malloc(sizeof(string));
T=(struct string *)malloc(sizeof(string));
S=creat();
T=creat();
n=KMP(S,T);
printf("%d",n);
}
在KMP函数中编译通不过?
指教啊……
#include<string.h>
#include<malloc.h>
#define MAX 80
typedef struct string{
int length;
char s[MAX];
}*string;
creat()
{
string s;
s=(struct string *)malloc(sizeof(string));
gets(s->s);
s->length=strlen(s->s);
return s;
}
void get_next(string T)
{
int *next[MAX];
int i=1,j=0;
next[1]=(int*)malloc(sizeof(int));
*next[1]=0;
while(i<(T->length)){
if(j==0||(T->s[i]==T->s[j])){
i++;j++;
next[i]=(int *)malloc(sizeof(int));
*next[i]=j;
}
else j=*next[j];
}
}
int KMP(string S,string T)
{
int pos,i,j;
get_next(T);
i=pos;j=1;
while(i<=S->s[0]&&j<=T->s[0]){
if(j==0||S->s[i]==T->s[j]){
i++;j++;
}
else j= *next[j];
}
if(j>(T->length)) return (i-(T->length));
else return 0;
}
main()
{
int n;
string S,T;
S=(struct string *)malloc(sizeof(string));
T=(struct string *)malloc(sizeof(string));
S=creat();
T=creat();
n=KMP(S,T);
printf("%d",n);
}
在KMP函数中编译通不过?
指教啊……