马拉车
先放一个链接 Link
首先,马拉车算法是为了解决最大回文串的问题而产生的,时间复杂度为
定义一个数组
定义
'R' means the address of the rightest letter of the axisymmetric(轴对称的) string which includes the i-th letter.
定义
'C' means the address of the axis of symmetry of the axisymmetric(轴对称的) string which includes the i-th letter.
It's easy to find out that R and C are in the same string.
那么如何求出
We can define
And in some cases
We only think about the cases in which
There are two cases.
- 当前以
为中心的回文串的右端点超过了 ,即 是因为扩展到左端点而结束的
非常优美的算法,非常简洁的代码
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1e6 + 9;
int len,C,R,maxlen;
int P[N<<1];
char c[N],T[N<<1];
int main()
{
scanf(" %s",c+1);
T[0]='^';
len=strlen(c+1);
for(int i=1;i<=len;i++){
T[i*2-1]='#';
T[i*2]=c[i];
}
T[2*len+1]='#';
T[2*len+2]='&';
for(int i=2;i<=2*len;i++){
int i_mirror;
i_mirror=2*C-i;
if(R>i){
P[i]=min(R-i,P[i_mirror]);
}
else{
P[i]=0;
}
while(T[i+P[i]+1]==T[i-P[i]-1]){
P[i]++;
}
if(i+P[i]>R){
C=i;
R=i+P[i];
}
}
for(int i=2;i<=2*len;i++){
if(P[i]>maxlen){
maxlen=P[i];
}
}
printf("%d\n",maxlen);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗