hdu 2203 (kmp)

#include <stdio.h>
#include <string.h>
char str[100000];
char str1[100000];
char str2[200000];
int next[100000];
void getNext(int m)
{
    int i=1,j=0;
    while(i<m)
    {
        if(j==0||str1[i]==str1[j])
        {
            i++,j++;
            if(str1[i]==str1[j])
                next[i]=next[j];
            else
                next[i]=j;
        }
        else
            j=next[j];
    }
}
void kmp(int m,int n)
{
    int i=0,j=0;
    while(i<n&&j<m)
    {
        if(j==0||str2[i]==str1[j])
            ++j,++i;
        else
            j=next[j];
    }    
    if(j>=m)
        puts("yes");
    else
        puts("no");
}
int main()
{
    int m,n;
    while ( gets(str) ) {
        gets(str1);
        strcpy(str2, str);    
        strcat(str2, str);
        m=strlen(str1);
        n=strlen(str2);
        getNext(m);
        kmp(m,n);
    }
}        

posted on 2011-07-28 09:08  ljfbest  阅读(86)  评论(0)    收藏  举报

导航