hdu 2203 亲和串(给两个字符串s1,s2,问s2可不可能出现在以s1为循环节的串中)

1.strcat函数,strcat(char *s , char *p);注意这里的s和p所指内存区域不可以重叠s必须有足够的空间来容纳p的字符串

2.strcpy函数,strcpy(char *s,char *p),将p拷贝到s

3.代码:

#include<cstdio>
#include<cstring>
using namespace std;

char s1[1000000],s2[100005],t[1000000];
int len1,len2;
//int LCPS[100005];
int next[100005];

void GetLCPS()
{
    int j=0;
    int k=-1;
    next[0]=-1;
    while(j<len2)
    {
        if(k==-1||s2[k]==s2[j])
        {
            //LCPS[j++]=++k;
            j++;
            ++k;
            next[j]=k;
        }
        else
        {
            //if(k-1>=0)
            k=next[k];
            //else
            //    k=-1;
        }
    }

}

void KMP()
{
    int i=0;
    int j=0;
    while(i<len1&&j<len2)
    {
        if(j==-1||s1[i]==s2[j])
        {
            j++;
            i++;
        }
        else
            j=next[j];
    }
    if(j==len2)
        printf("yes\n");
    else
        printf("no\n");
}

int main()
{
    while(scanf("%s%s",s1,s2)==2)
    {
        len1=strlen(s1);
        len2=strlen(s2);
        while(len1<len2)
        {
            strcpy(t,s1);
            strcat(s1,t);
            len1=strlen(s1);
        }
        strcpy(t,s1);
        strcat(s1,t);
        len1=strlen(s1);
        GetLCPS();
        KMP();
    }
    return 0;
}


你可能感兴趣的:(KMP)