KMP算法

#include <stdio.h>

struct SeqString {
        int MAXNUM;
        int n;
        char *c;
};
typedef struct SeqString * PSeqString;


PSeqString createNullStr_seq(int m)
{
        PSeqString pstr = (PSeqString)malloc(sizeof(struct SeqString));
        if(pstr !=NULL)
        {
                pstr->c = (char *)malloc(sizeof(char)*m);
                if(pstr->c)
                {
                        pstr->n=0;pstr->MAXNUM=m;
                        return (pstr);
                }
                else free(pstr);
        }
        printf("Out of space!/n");
        return NULL;
}

makeNext(PSeqString p,int *next)
{
        int i=0,k=-1;
        next[0] = -1;
        while(i<(p->n-1))
        {
                while(k>=0 && p->c[i]!=p->c[k]) k=next[k];

                i++;k++;
                if(p->c[i] == p->c[k]) next[i]=next[k];
                else next[i]=k;
        }
}
int pMatch(PSeqString t,PSeqString p,int *next)
{
        int i=0,j=0;
        while(i < p->n && j < t->n)
        {
                if( i==-1 || p->c[i] == t->c[j])
                {i++;j++;}
                else    i=next[i];
        }
        if(i > p->n) return (j - p->n + 1);
        else return(0);

}
int main()
{
        PSeqString s;
        int next[9],i=0;
        s = createNullStr_seq(9);
        s->c[0] = 'a';
        s->c[1] = 'b';
        s->c[2] = 'c';
        s->c[3] = 'a';
        s->c[4] = 'b';
        s->c[5] = 'b';
        s->c[6] = 'a';
        s->c[7] = 'b';
        s->c[8] = 'c';
        s->n = 9;
        makeNext(s,next);
        for(i=0;i<9;i++)
                printf("%d/n",next[i]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值