题目描述
给定一个字符串S,要求你找到一个最长的子串,它既是S的前缀,也是S的后缀,并且在S的内部也出现过(非端点)
题解
KMP的失配函数fail[i]的值就是s[0..i]的最长前缀且是后缀的长度~~~,因此我们从S的末尾位置开始沿着失配函数跑即可,对于当前fail[i],判断前缀s[0…i]是否在s[i+1..length(s)-i]是否出现即可~~~~如果存在则是最长子串的长度,否则继续判断长度为fail[fail[i]]的前缀是否符合上述情况,一直到找到就OK了。。。
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
ll len,t;
char s[1000006];
int next_s[1000006];
void getnext(){
memset(next_s,0,sizeof(next_s));
int i=0,j=-1;
next_s[0]=-1;
while(i<=len){
if(j==-1||s[i]==s[j])next_s[++i]=++j;
else j=next_s[j];
}
}
int main(){
scanf("%lld",&t);
while(t--){
scanf("%s",s);
len=strlen(s);
getnext();
int p;
bool flag=false;
//一步步缩小前缀和后缀,flag标志是否找到符合条件的模式串
for(p=next_s[len];p>0;p=next_s[p]){
if(p*3>len)continue;
//找到的前缀和后缀是s[0]~s[p-1]=s[len-p]~s[len-1];
for(int i=p,j=0;i<len-p;){//在区间[p,len-p)中进行KMP匹配找出的模式串(上一行)
if(j==-1||s[i]==s[j]){
i++;j++;
if(j==p){
flag=true;
break;
}
continue;
}
j=next_s[j];
}
if(flag)break;
}
if(!flag)printf("0\n");
else printf("%d\n",p);
}
return 0;
}
// /\ | / |**、
// / \ | / | \
// / \ |/ | / _____ ____ | /
// /------\ |\ |__/ / \ \ /\ / / \ | /
// / \ | \ | / \ \ / \ / /______\ |/
// / \ | \ | \ / \ / \ / \ |
// / \ | \ | \_____/ \/ \/ \_____ |
/**
* ┏┓ ┏┓
* ┏┛┗━━━━━━━┛┗━━━┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*/
// warm heart, wagging tail,and a smile just for you!
//
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// .' \| |// `.
// / \||| : |||// \
// / _||||| -:- |||||- \
// | | \\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//