太菜了,参考大佬的博客知道了解题思路。
题意很简单,要求插入一定数目的字符使给定字符串成为回文字符串,问最小数目?这道题一个良好的解法是求给定字符串以及其逆串的最长公共子序列,用串长减去最长公共子序列就是结果。(不知道怎么证明的,但是一想貌似是对的)
下一个重点是dp数组的存储,有两种方式,使用short int型数字和滚动数组,先附上short int 型代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
const int maxn=5005;
short int dp[maxn][maxn];
int n;
string str1;
string str2;
int lenth1,lenth2;
void lcs()
{
memset(dp,0,sizeof(dp));
lenth1=str1.length();//length返回string中字符的个数
lenth2=str2.length();
for(int i=0; i<=lenth1; i++)
for(int j=0; j<=lenth2; j++)
{
if(i==0||j==0)
dp[i][j]=0;
else if(str1[i-1]==str2[j-1])
dp[i][j]=dp[i-1][j-1]+1;