回文字符串(LCS变形)

回文字符串

 

 思路:由于要找最少添加的字符使得原字符串变为回文串,那么先将给出的字符串反转,将两字符串做 LCS,得到的是最大的公共子串的长度,那么用字符串长度减去最大公共子串长度就是最少添加字符的个数

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 #include <cstring>
 5 #include <string>
 6 #include <cmath>
 7 #include <cstdlib>
 8 #include <algorithm>
 9 using namespace std;
10 typedef long long ll;
11 const int maxn = 1010;
12 
13 char s[maxn],ss[maxn];
14 int dp[maxn][maxn];
15 
16 int main()
17 {
18     scanf("%s",s);
19     int len1=strlen(s);
20     for(int i=0;i<len1;i++){
21         ss[i]=s[len1-i-1];
22     }
23 
24     for(int i=1;i<=len1;i++){
25         for(int j=1;j<=len1;j++){
26             if( s[i-1]==ss[j-1] ) dp[i][j]=dp[i-1][j-1]+1;
27             else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
28         }
29     }
30     printf("%d\n",len1-dp[len1][len1]);
31     return 0;
32 }

 

posted @ 2020-01-31 09:21  swsyya  阅读(217)  评论(0编辑  收藏  举报

回到顶部