链接: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;
}