hdu 1841 KMP运用


给你两个字符串  求最小包含这两个字符串的字符串的长度     分别把两个字符串作模式串和文本串   然后进行匹配  注意判断条件就行了

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;

char str1[1000010],str2[1000010],str3[1000010];
int next[1000010];
int deal(char str[],int len)
{
    memset(next,0,sizeof(next));
    next[0]=-1;
    int i=0,k=-1;
    while(i<len-1)
    {
        if(k==-1||str[i]==str[k])
        {
            i++;
            k++;
            next[i]=k;
        }
        else k=next[k];
    }    
    return 0;
}
int find(char str1[],char str2[],int len1,int len2)
{
    int i,j;
    i=0,j=0;
    int k=-1;
    while(j<len2&&i<len1)
    {
        if(str1[i]==str2[j]||j==-1)
        {
            i++;
            j++;
            if(j>k&&i==len1||j==len2) k=j;//注意着就行了
        }
        else j=next[j];
    }
    return k;
}
int main()
{
    int T,i,j,t;
    scanf("%d",&T);
    while(T--)
    {
        int Max=-1;
        scanf("%s%s",str1,str2);
        int len1=strlen(str1);
        int len2=strlen(str2);
        deal(str2,len2);
        int t=find(str1,str2,len1,len2);
        Max=Max<t?t:Max;
        deal(str1,len1);
        t=find(str2,str1,len2,len1);
        Max=Max<t?t:Max;
        printf("%d\n",len1+len2-Max);
    }    
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值