codeforces 126B password KMP

/*
    题目描述:给出一个字符串s,从s中找一个子串s0,使得s0是满足既是s前缀、又是s后缀,还是s的一个非前缀非后缀的
            子串这三个条件的长度最长的串
               
    思路:利用KMP,找出能匹配s前缀的最长的一段长度,其长度为ans1,注意这段匹配的结尾不能是s的最后一个字符,
        否则这段匹配就成了s的一个后缀;然后再找出能匹配前缀的最长后缀,其长度为ans2,如果ans2>ans1,就执行
        ans2 = f[ans2] ,此时的s[0 , 1 , ... ,ans2 - 1]仍然既是s的前缀又是s的后缀,这一操作一直执行到ans2 <= ans1或
        者ans2 == 0结束,如果ans2==0,那么输出Just a legend , 否则输出s[0 , 1,  ...  , ans2 - 1 ] 
*/
#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps=1e-6;
const int maxn = 1e6 + 5 ;
char s1[maxn] , s2[maxn];
int f[maxn] , flag , pos ;
void getFail(char * P , int * f)
{
    int m = strlen(P);
    f[0] = f[1] = 0;
    for(int i = 1 ; i< m ; i++){
        int j = f[i] ;
        while(j && P[i]!=P[j])
            j = f[j] ;
        if(P[i] == P[j])    f[i + 1]  = j + 1 ;
        else                  f[i + 1] = 0;
    }
}
int KMP(char * T , char * P , int * f)
{
    int n = strlen(T) , m = strlen(P) ;
    int j = 0 , ans1 = -1 , ans2 ;
    getFail(P , f);
    for(int i = 0 ; i< n ; i++){
        while(j && T[i] != P[j])
            j = f[j];
        if(T[i] == P[j])
            ++j;
        if(j > ans1 && !(i == n - 1) ){
            ans1 = j;
        }
    }
    ans2 = j ;
    while(ans1 < ans2 && ans2 != 0){
        ans2 = f[ans2] ;
    }
    return ans2 ;
}
int main()
{
    scanf("%s",s1);
    mem(f , 0);
    int ans = KMP(s1 + 1 , s1 , f) ;
    if(!ans){
        printf("Just a legend\n");
        return 0;
    }
    for(int i = 0 ; i<ans ; i++){
        printf("%c",s1[i]);
    }
    printf("\n");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值