hdu2594 Simpsons’ Hidden Talents

来源:互联网 发布:网络英雄洛克人粤语版 编辑:程序博客网 时间:2024/06/04 19:39

题目链接: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;    }    


原创粉丝点击