码蹄集2177--密码

 

next数组用于判断又是S的前缀又是S的后缀,所以剩下的需要解决:

1.找到S的各种前缀和后缀,从最长的向最短的考虑

例如:

                    a   b  c  a  b  c  a  b  c

next数组:  -1  0  0  0  1  2  3  4  5  6

那么最长的前后缀长度为6,第二长的是next[6]=3,第三长的是next[3]...

2.在一种前缀和后缀的情况下,看中间是否有相同的字符串,运用到strstr函数,strstr(a,b)判断字符串a是否含有字符串b。

血的教训:

1.strlen用多了会疯狂超时!!!

2.strncpy(a,b+2,10)----将b字符串的第三个字符开始取10个字符赋值给a

每次循环赋值后需要填写 a[10]=‘\0’;

#include<bits/stdc++.h> 

using namespace std;

int next_[1000010];
char s[1000010];  //原串
char t[1000010];//目标串
char s_temp[1000010];//s的临时串--去头去尾



void find_next(int len){//求s的next数组
    int i=0,j=-1;
    next_[0]=-1;
    while(i<=len){
        if(j==-1||s[i]==s[j]){
            i++;
            j++;
            next_[i]=j;
        }
        else{
            j=next_[j];
        }
    }
}

int main( )
{
    cin>>s;
    int len=strlen(s);
    find_next(len);
    if(next_[len]==0){
        cout<<"Just a legend";
        return 0;
    }
    int temp=next_[len];
    strcpy(s_temp,s+1);
    s_temp[strlen(s_temp)-1]='\0';
    while(temp!=0){
        //cout<<"temp:"<<temp<<endl;
        strncpy(t,s,temp);
        t[temp]='\0';
        //cout<<t<<endl;
        //cout<<s_temp<<endl;
        if(strstr(s_temp,t)){
            cout<<t;
            return 0;
        }
        temp=next_[temp];
    }
    
    cout<<"Just a legend";

    
    return 0;
}

     

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值