拓展KMP

#include<stdio.h>
#include<string.h>

int next[100010],ex[100010];
void getnext(char *str)
{
    int i=0,j,po,len=strlen(str);
    next[0]=len;
    while(str[i]==str[i+1]&&i+1<len)
    {
        i++;
    }

    next[1]=i;
    po=1;
    for(i=2; i<len; i++)
    {
        if(next[i-po]+i<next[po]+po)
        {
            next[i]=next[i-po];
        }
        else
        {
            j=next[po]+po-i;
            if(j<0)
                j=0;
            while(i+j<len&&str[j]==str[j+i])
            {
                j++;
            }
            next[i]=j;
            po=i;
        }
    }
}
void exkmp(char *s1,char *s2)
{
    int i=0,j,po,len1=strlen(s1),len2=strlen(s2);
    getnext(s2);
    while(s1[i]==s2[i]&&i<len2&&i<len1)
        i++;
    ex[0]=i;
    po=0;
    for(i=1; i<len1; i++)
    {
        if(next[i-po]+i<ex[po]+po)
            ex[i]=next[i-po];
        else
        {
            j=ex[po]+po-i;
            if(j<0)
                j=0;
            while(i+j<len1&&j<len2&&s1[j+i]==s2[j])
            {
                j++;
            }
            ex[i]=j;
            po=i;
        }
    }
}

//求出s1[i..len(s1)]与s2的最长公共前缀长度
int main()
{
int len1,len2;
    char s1[120000],s2[120000];
    scanf("%s",s1);
    scanf("%s",s2);
    exkmp(s1,s2);
    len1 = strlen(s1);
    len2 = strlen(s2);

    for(int i = 0; i < len2; i ++)//s2的next数组
    {
        if(i == len2 -1)
            printf("%d\n",next[i]);
        else
            printf("%d ",next[i]);
    }

    for(int i = 0; i < len1; i ++)
    {
        if(i == len1-1)
            printf("%d\n",ex[i]);
        else
            printf("%d ",ex[i]);
    }

    printf("\n");


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值