传送门:https://ac.nowcoder.com/acm/contest/549/B
思路:题目要求可以把字符断开再接上,我们可以直接接上,也就是让str=str+str;之后就是对字符串求最长回文串。有两种办法——DP和马拉车。当然最后要知道无论怎么断链都不可能超过原有的字符串长度。
第一种是用DP,DP的边界是一个或两个相连字母相同。
#include<bits/stdc++.h>
using namespace std;
int dp[10008][10008];
string str;
int main() {
cin>>str;
str=str+str;
int len=str.length(),ans=0,s,e;
for(int i=0;i<len;i++){
dp[i][i]=1;
if(str[i]==str[i+1]){
dp[i][i+1]=1;
ans=2;
}
}
for(int k=3;k<=len;k++){ //子串的长度
for(int i=0;i+k-1<len;i++){ //子串左端点
int j=i+k-1; //子串右端点
if(str[i]==str[j]&&dp[i+1][j-1]){
dp[i][j]=1;
ans=k;
s=i;e=j; //保存最长回文子串的下标
}
}
}
cout<<min(ans,len/2)<<endl;
return 0;
}