牛客竞赛 字符串的问题

链接:https://ac.nowcoder.com/acm/problem/15165
来源:牛客网

题目描述
有一个字符串 让你找到这个字符串 S 里面的子串T 这个子串 T 必须满足即使这个串的前缀 也是这个
串的后缀 并且 在字符串中也出现过一次的(提示 要求满足前后缀的同时也要在字符串中出现一次 只是前后缀可不行 输出最长满足要求字符串)
输入描述:
给出一个字符串 长度 1 到 1e6 全部是小写字母
输出描述:
如果找的到就输出这个子串T 如果不行就输出 Just a legend
示例1
输入

fixprefixsuffix

输出

fix

示例2
输入

abcdabc

输出

Just a legend

哇要注意不能用next数组,- -用了就编译错误,wa了好多发。
就是一个kmp练习题,求出next就差不多了
Code:

#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn =1e6 + 5;
string s;
int nxt[maxn];
int slen=0;
void get_next()
{
    nxt[0]=-1;
    int k=-1,j=0;
    while(j<slen)
    {
        if(k==-1||s[j]==s[k])
        {
            j++;
            k++;
            nxt[j]=k;
        }
        else
            k=nxt[k];
    }
}
bool kmp(int len)
{
    for(int i=1,j=0; i<slen-1; i++)
    {
        while(j>0&&s[i]!=s[j])
            j=nxt[j];
        if(s[i]==s[j])
            j++;
        if(j==len)
            return true;
    }
    return false;
}
bool help(int len)
{
    for(int j=0; j<len; j++)
    {
        if(s[j]!=s[slen-len+j])
            return false;
    }
    return true;
}
bool work()
{
    for(int j=slen-2; j>=1; j--)
    {
        if(help(j))
        {
            if(kmp(j))
            {
                for(int k=0; k<j; k++)
                    printf("%c",s[k]);
                return true;
            }

        }
    }
    return false;
}

int main()
{
    cin>>s;

    slen=s.size();
    get_next();
    if(!work())
        printf("Just a legend");
    return 0;
}

Code2:

#include <queue>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstring>
#include<stack>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn =  1e6+5;

char str[maxn],tmp1[maxn],tmp2[maxn],tmp3[maxn];

int main()
{
    scanf("%s",str);
    int len=strlen(str);
    int ans=-1;
    if(len==1)ans=-1;
    else
    {
        for(int i=0; i<len; i++)
        {
            strncpy(tmp1,str,i+1);
            strncpy(tmp2,str+len-1-i,i+1);
            strncpy(tmp3,str+1,len-2);
             // cout<<tmp1<<" "<<tmp2<<" "<<tmp3<<endl;
              char *tmp=strstr(tmp3,tmp1);
              //cout<<tmp<<endl;
            if(strcmp(tmp1,tmp2)==0&&tmp!=NULL)
            ans=max(ans,i+1);

        }
    }
    if(ans==-1)printf("Just a legend\n");
    else
    {
        for(int i=0;i<ans;i++)printf("%c",str[i]);
        printf("\n");
    }

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值