51nod--1092 回文字符串(非连续!)

来源:互联网 发布:头脑风暴软件 编辑:程序博客网 时间:2024/06/05 06:37

题目:

      回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。每个字符串都可以通过向中间添加一些字符,使之变为回文字符串。
例如:abbc 添加2个字符可以变为 acbbca,也可以添加3个变为 abbcbba。方案1只需要添加2个字符,是所有方案中添加字符数量最少的。

Input
输入一个字符串Str,Str的长度 <= 1000。
Output
输出最少添加多少个字符可以使之变为回文字串。
Input示例
abbc
Output示例
2
注意: 注意本题和1088最长回文子串的区别,本题也是通过构造原字符串的逆序串,但本题在对原串和逆序串匹配的过程中,用到的是dp! , 本题在匹配过程中并不需要1088中匹配的要求的连续性! 此点区分好,卡了些久~ 然后 本题思路就是 : 用字符串总长减去 匹配上的字符串的长度(LCS算法思想)
 关键代码:
         if(s[i] == ss[j]) dp[i+1][j+1] = dp[i][j]+1;            else dp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j]);
完整代码:
 #include <iostream>#include <cstring>#include <algorithm>using namespace std;int dp[1005][1005];int main(){    string s,ss;    cin >> s;    ss = s;    reverse(ss.begin(),ss.end());    int len = ss.size();    memset(dp,0,sizeof(dp));    for(int i=0; i<s.size(); i++)        for(int j=0; j<ss.size(); j++)        {            if(s[i] == ss[j]) dp[i+1][j+1] = dp[i][j]+1;            else dp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j]);        }    cout <<  len-dp[len][len] << endl;    return 0;}