A Subsequence is a sequence obtained by deleting zero or more characters in a string. A Palindrome is
a string which when read from left to right, reads same as when read from right to left. Given a string,
find the longest palindromic subsequence. If there are many answers to it, print the one that comes
lexicographically earliest.
Constraints
• Maximum length of string is 1000.
• Each string has characters ‘a’ to ‘z’ only.
Input
Input consists of several strings, each in a separate line. Input is terminated by EOF.
Output
For each line in the input, print the output in a single line.
Sample Input
aabbaabb
computer
abzla
samhita
Sample Output
aabbaa
c
aba
aha
题意:给定一个字符串,求出去掉某些字符后的最长回文串,如果长度相同则输出字典序最小的回文串。
思路:原串翻转后和原串的最长公共子序列就是最长回文串。状态转移时可以处理字典序最小问题。,这样转移也会导致得到的公共序列并不一定就是回文串,但是可以保证前半部分公共序列一定是回文串的前半部分,所以输出结果的时候注意根据公共序列长度的奇偶选择重复两次输出前半部分就好。
例如: kfclbckibbibjccbej
原串和反串得到的公共序列却是bcibbibc
就因为状态转移的时候按照字典序决定。
状态转移如下
如果s1[i]==s2[j] DP[i][j].len=DP[i-1][j-1].len+1,DP[i][j].str=DP[i-1][j-1].str+s1[i];
否则在DP[i-1][j],DP[i][j-1]中选择长度最大,字典序最小的转移到DP[i]][j]
代码
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
//最长公共子序列
const int maxn=1005;
struct node
{
int len;
string str;
} DP[maxn][maxn];
char str_1[maxn];
char str_2[maxn];
int main()
{
while(scanf("%s",str_1+1)!=EOF)
{
int len=strlen(str_1+1);
memset(str_2,'\0',sizeof(str_2));
for(int i=1,j=len; i<=len; i++,j--)
str_2[i]=str_1[j];//逆置字符串
for(int i=1; i<=len; i++)
{
for(int j=1; j<=len; j++)
{
DP[i][j].len=0;
DP[i][j].str.clear();
}
}
for(int i=1; i<=len; i++)
{
for(int j=1; j<=len; j++)
{
if(str_1[i]==str_2[j])
{
DP[i][j].len=DP[i-1][j-1].len+1;
DP[i][j].str=DP[i-1][j-1].str+str_1[i];
}
else
{
if(DP[i-1][j].len>DP[i][j-1].len)
{
DP[i][j].len=DP[i-1][j].len;
DP[i][j].str=DP[i-1][j].str;
}
else if(DP[i-1][j].len==DP[i][j-1].len)
{
DP[i][j].len=DP[i-1][j].len;
if(DP[i-1][j].str>DP[i][j-1].str)
DP[i][j].str=DP[i][j-1].str;
else
DP[i][j].str=DP[i-1][j].str;
}
else
{
DP[i][j].len=DP[i][j-1].len;
DP[i][j].str=DP[i][j-1].str;
}
}
}
}
// cout<<DP[len][len].str<<endl;
if(DP[len][len].len%2==0)
{
for(int i=0; i<DP[len][len].len/2; i++)
printf("%c",DP[len][len].str[i]);
}
else
{
for(int i=0; i<=DP[len][len].len/2; i++)
printf("%c",DP[len][len].str[i]);
}
for(int i=DP[len][len].len/2-1; i>=0; i--)
printf("%c",DP[len][len].str[i]);
// for(int i=0; i<DP[len][len].len; i++)
// printf("%c",DP[len][len].str[i]);
printf("\n");
memset(str_1,'\0',sizeof(str_1));
}
return 0;
}