HDU 2594

  这是一道简单的KMP求next数组的题,几乎不用动脑筋,可以用来练练手,直接把两个字符串连接在一起求next就行了,唯一要注意的就是长度不能大于原来任一字符串的长度,如果长度大于了,要选择len1和len2中较小的一个输出。

#include<stdio.h>
#include<string.h>
#define MAX_STR 50005
char str1[MAX_STR*2],str2[MAX_STR]; 
int next[MAX_STR*2];
void get_next(int,int);
int main()
{
    char oupt[MAX_STR];
    while(scanf("%s%s",str1,str2)!=EOF)
    {
    int len1=strlen(str1),len2=strlen(str2);
    strcat(str1,str2);
    get_next(len1,len2);
    int i;
    for(i=0;i<next[len1+len2];i++)
    {
        oupt[i]=str1[i];
    }
    oupt[i]='\0';
    if(next[len1+len2])
    {
        if(next[len1+len2]>len1||next[len1+len2]>len2)
        {
        if(len1>len2)
        {
            printf("%s %d\n",str2,len2);
        }
        else
        {
            oupt[len1]='\0';
            printf("%s %d\n",oupt,len1);
        }
        }
        else
        {
        printf("%s %d\n",oupt,next[len1+len2]);
        }
    }
    else
    {
        printf("0\n");
    }
    }
    return 0;
}
void get_next(int len1,int len2)
{
    int i=0,j=-1;
    next[0]=-1;
    while(i<len1+len2)
    {
    if(j==-1||str1[i]==str1[j])
    {
        i++;j++;
        next[i]=j;
    }
    else
    {
        j=next[j];
    }
    }
}
posted @ 2012-08-13 21:05  等待电子的砹  阅读(518)  评论(0)    收藏  举报