回文字符串

回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。每个字符串都可以通过向中间添加一些字符,使之变为回文字符串。
例如:abbc 添加2个字符可以变为 acbbca,也可以添加3个变为 abbcbba。方案1只需要添加2个字符,是所有方案中添加字符数量最少的。
现在,给定一个字符串,求能够使其变为回文串最少要添加几个字符?
#include <cmath>
#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;

int main() { 
    string s,t;
    cin>>s;
    t=s;
    reverse(s.begin(),s.end());
    int n=s.size();
    vector<vector<int>>f(n+1,vector<int>(n+1,0));
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++){
            if(s[i-1]==t[j-1])f[i][j]=f[i-1][j-1]+1;
            else f[i][j]=max(f[i-1][j],f[i][j-1]);
        }
     cout<<n-f[n][n]<<endl;
    

    return 0;
}

 

posted @ 2019-07-20 00:07  YF-1994  阅读(2476)  评论(0编辑  收藏  举报