hdu2594 简单KMP

题意:
     给你两个串,问你s1的前缀和s2的后缀最长公共部分是多少。
思路:

     根据KMP的匹配形式,我们求出s1的next,然后用s1去匹配s2,输出当匹配到s2的最后一个的时候的匹配位置就行了。


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

#define N 50000 + 10

char stra[N] ,strb[N];
int next[N];

void get_next(int m)
{
     int j ,k;
     j = 0 ,k = -1;
     next[0] = -1;
     while(j < m)
     {
         if(k == -1 || strb[j] == strb[k])
         next[++j] = ++k;
         else k = next[k];
     }
}

int KMP(int n ,int m)
{
    int max = 0;
    int i ,j;
    for(i = j = 0 ;i < n ;)
    {
        if(stra[i] == strb[j])
        {
           i ++ ,j ++;
        }
        else
        {
           j = next[j];
           if(j == -1)
           {
                j = 0;
                i ++;
           }
        }
    }
    return j;
}

int main ()
{
    int n ,m;
    while(~scanf("%s %s" ,strb ,stra))
    {
       n = strlen(stra);
       m = strlen(strb);
       get_next(m);
       int ans = KMP(n ,m);
       if(!ans) printf("0
");
       else printf("%s %d
" ,stra + n - ans ,ans);
       
    }
    return 0;
}
        
                 


原文地址:https://www.cnblogs.com/csnd/p/12063101.html