优化next数组后的 KMP算法

#include<iostream>
#include<stdio.h>
using namespace std;
const int Max=50;

typedef class NOde
{
public :
char a[Max];
int length;
}Bunch;
void printlist(Bunch &L);
void creat(Bunch &L,char t[]);
void gets_next_arry(Bunch &L,int news[Max]);
int  KMP(Bunch &L1,Bunch &L2,int next[]);
int main()
{
Bunch L1,L2;
char t[Max];
gets(t);
creat(L1,t);
printlist(L1);
gets(t);
creat(L2,t);
printlist(L2);
int next[L2.length];
gets_next_arry(L2,next);
for(int i=0;i<L2.length;i++)
{
cout<<next[i]<<"  ";
}
cout<<endl;
cout<<"L2在L1的"<<KMP(L1,L2,next)<<"个位置"<<endl;
return 0;

}


void creat(Bunch &L,char t[])
{
int i=0;
while(t[i]!='\0')

{
L.a[i]=t[i];
i++;
}

L.a[i]='\0';
L.length=i;
}


void printlist(Bunch &L)
{

int i=0;
while(L.a[i]!='\0')
{
    cout<<L.a[i];
    i++;
}
cout<<endl;
}

void gets_next_arry(Bunch &L,int next[])

{
    next[0]=-1;
    int k=-1;
    int i=0;
    while(i<L.length)

    {
        if((k==-1)||(L.a[i]==L.a[k]))
        {
            i++;
            k++;
            if(L.a[i]!=L.a[k])
            {
                next[i]=k;
            }
            else
            {
                    //    k=next[k];不要改变K的值
               next[i]=next[k];
            }

        }

        else
        {

            k=next[k];
        }
    }

}

int KMP(Bunch &L1,Bunch &L2,int next[])

{
int i=0,j=0;
while((j<L2.length)&&(i<L1.length))
{

    if(L1.a[i]==L2.a[j]||(j==-1))

    {
        i++;
        j++;
    }

    else
    {
        j=next[j];

    }

}

if(j==L2.length)

    {
        return i-j+1;
    }

else

    {
        return -1;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值