给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
输出需要删除的字符个数。
经典编程题目啦~~
设原字符串s
原字符串反转的字符串t,回文串最长长度问题转为求LCS(s,t)的长度,画个二维数组就能明白原理,dp[i][j]表示 s 前 i 个字符与 t 前 j 个的公共最长子序列(LCS)长度
so easy~
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
const int maxn = 1005;
int dp[maxn][maxn];
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
string s;
memset(dp,0,sizeof(dp));
while(cin>>s)
{
string t = s;
reverse(s.begin(),s.end());
//cout<<s<<endl;
int len = s.length(),maxlen = 0;
for(int i=0;i<len;++i){//第一行预处理
if(t[0]==s[i]){
while(i<len)dp[0][i++] = 1;
}
else dp[0][i] = 0;
}
for(int i=0;i<len;++i){//第一列预处理
if(t[i]==s[0]){
while(i<len)dp[i++][0] = 1;
}
else dp[i][0] = 0;
}
for(int i=1;i<len;++i)
{
for(int j=1;j<len;++j)
{
if(s[j] == t[i])dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
maxlen = max(maxlen,dp[i][j]);
}
}
//cout<<maxlen<<endl;
cout<<len-maxlen<<endl;
}
return 0;
}
这是一个编程题目,目标是确定如何从给定字符串中删除最少的字符,使其变成回文串。通过将原字符串与其反转字符串进行比较,并寻找最长公共子序列(LCS),可以找到解决方案。该问题来源于腾讯2017年暑期实习编程题。
263

被折叠的 条评论
为什么被折叠?



