最长回文子串:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e5+10;
char s[maxn];
char s2[maxn*2];
int p[maxn*2];
void Man(){
memset(p,0,sizeof(p));
int mx = 0 ,id=0;
for(int i=0;s2[i]!='\0';i++){
p[i] = mx > i ?min(p[2*id-i],mx-i ):1;
while(s2[i+p[i]] == s2[i-p[i]]) p[i]++;
if(p[i] + i > mx){
mx = p[i] + i;
id = i;
}
}
}
int main(){
while(scanf("%s",s)!=EOF){
s2[0] = '$';
int len = strlen(s);
int c = 1;//注意这里 == 1
for(int i=0;i<len;i++){
s2[c++] = '#';
s2[c++] = s[i];
}
s2[c++] ='#';
s2[c] = '\0';
Man();
int ans = 1;
for(int i=0;i<c;i++)
ans = max(ans,p[i]);
printf("%d\n",ans-1);
}
return 0;
}
最长回文子序列:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e4+10;
char a[maxn];
int dp[maxn][maxn];
int seq(char s[])
{
int n = strlen(s);
for(int i=n-1;i>=0;i--){
dp[i][i] = 1;
for(int j=i+1;j<n;j++){
if(s[i] == s[j])
dp[i][j] = dp[i+1][j-1]+2;
else
dp[i][j] = max(dp[i+1][j],dp[i][j-1]);
}
}
return dp[0][n-1];
}
int seqcount(char s[])
{
int n = strlen(s);
for(int j=0;j<n;j++){
dp[j][j] = 1;
for(int i=j-1;i>=0;i--){
dp[i][j] = dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];
if(s[i] == s[j])
dp[i][j] += 1 + dp[i+1][j-1];
}
}
return dp[0][n-1];
}
int main()
{
while(~scanf("%s",a))
{
cout<<seq(a)<<endl;//最长回文子序列的长度
cout<<seqcount(a)<<endl;//最长回文子序列的个数
}
return 0;
}