hdu2594 Simpsons’ Hidden Talents

本文介绍了一种使用KMP算法寻找两个字符串间最长前缀匹配的方法。通过实例演示了如何实现KMP算法,并提供了完整的C语言代码。适用于需要解决字符串匹配问题的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2594


题解:finds the longest prefix of s1 that is a suffix of s2. s1作为模式串 s2作为原串,进行KMP 


#include <stdio.h>      
#include <string.h>      
#define MAXN 50002    
      
int next[MAXN],len1,len2;      
char str1[MAXN],str2[MAXN];      
  
void getNext()      
{      
    int i=0,j=-1;       
    next[0]=-1;      
    while(i<len2)      
    {      
        if (j==-1||str2[i]==str2[j])      
        {      
            i++;      
            j++;      
            next[i]=j;      
        }      
        else      
            j=next[j];      
    }      
}      
      
int KMP()      
{      
    int i,j;      
    i=j=0;  
    getNext();  
    while(i<len1&&j<=len2)      
    {      
        if(j==-1||str1[i]==str2[j])      
        {      
            i++;      
            j++;     
        }      
        else      
            j=next[j];    
    }      
	return j;
}      
    
int main()    
{    
    int n,i; 
	while (scanf("%s %s",str2,str1)!=EOF)
	{
		len1=strlen(str1);
		len2=strlen(str2);
		n=KMP();
		if(n==0)
			printf("0\n");
		else
		{
			for(i=0;i<n;++i)
				printf("%c",str2[i]);
			printf(" %d\n",n);
		}
	}
    return 0;    
}    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值