nyoj327亲和串(kmp)

亲和串
时间限制:1000 ms  |  内存限制:65535 KB
难度:3
描述
最近zyc遇到了一个很棘手的问题:判断亲和串,以前判断亲和串的时候直接可以看出来,但现在不同了,现在给出的两字符串都非常的大,看的zyc头都晕了。于是zyc希望大家能帮他想一个办法来快速判断亲和串。亲和串定义:给定两个字符串s1和s2,如果能通过s1循环移动,使s2包含在s1中,那么我们就说s2是s1的亲和串。
输入
本题有多组测试数据,每组数据的第一行包含输入字符串s1,第二行包含输入字符串s2,s1与s2的长度均小于100000。
输出
如果s2是s1的亲和串,则输出"yes",反之,输出"no"。每组测试的输出占一行。
样例输入
AABCD
CDAA
ASD
ASDF
样例输出
yes

no

 
#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
char s[1000005],s1[1000005],a[1000005];
int nex[1000005];
void get_next(char t[])
{
    int i=0,j=-1;
    nex[0]=-1;
    while(i<strlen(t))
    {
        if(t[i]==t[j]||-1==j)
        {
            i++;
            j++;
            if(t[i]!=t[j])
            {
                nex[i]=j;
            }
            else
            {
                nex[i]=nex[j];
            }
        }
        else
        {
            j=nex[j];
        }
    }
}
int kmp(char s[],char t[],int pos)
{
    get_next(t);
    int x=strlen(s);
    int y=strlen(t);
    int i=pos,j=0;
    while(i<x&&j<y)
    {
        if(j==-1||t[j]==s[i])
        {
            i++;
            j++;
        }
        else
        {
            j=nex[j];
        }
    }
    if(j==y)
    {
        return 1;
    }
    else
        return 0;
}
int main()
{
    while(~scanf("%s%s",a,s1))
    {
        memset(nex,-1,sizeof(nex));
        strcpy(s,a);//把a串复制给c
        strcat(s,a);//把a串添加到s的后面
        int l=strlen(a),ll=strlen(s1);
        if(l<ll)
        {
            printf("no
");//第一个字符串的长度不能小于第二个的长度
            continue;
        }
        int ans=kmp(s,s1,0);
        if(ans==0)
            printf("no
");
        else
            printf("yes
");
    }
}
        


原文地址:https://www.cnblogs.com/da-mei/p/9053337.html