版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w419387229/article/details/82079693
求字符串最长回文子串
Manacher具体思想:https://www.cnblogs.com/z360/p/6375514.html
#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
#include<algorithm>
using namespace std;
int p[2500];
void Manacher(string s, int len){
int right = 0, ans = 0, pos = 0;
for(int i = 1; i < len; ++i){
if(right > i)//对称点回文长度的基础上开始往下匹配
p[i] = min(p[2*pos-i],right-i);
else//已经在right外,这个只会是新的,从头开始匹配
p[i] = 1;
//无论何种情况都需要继续匹配
while(i + p[i] < len && i - p[i] >= 0 && s[i-p[i]] == s[i+p[i]])
++p[i];
if(p[i] + i > right){
right = p[i] + i;
pos = i;
}
ans = max(p[i], ans);
}
cout << (ans-1);
}
int main(){
string s,str;
int len;
getline(cin,s);
len = s.length();
for(int i = 0; i <len; ++i){
str.push_back('#');
str.push_back(s[i]);
}
str.push_back('#');
Manacher(str, 2*len+1);
return 0;
}