POJ 1159 字符串匹配问题

题目大意:

问至少添加几个字符才能保证这个字符串是个回文串

一开始想也想不到字符串匹配上,因为是找回文串,我们可以把已给字符串逆向得到一个新的字符串,然后比较两者得到最大匹配长度,最后总长度减去最大匹配长度

就是所要求的值

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 #define N 5005
 7 char str[N],rev[N];
 8 short dp[N][N];
 9 void get_rev(int n,char *str)
10 {
11     int cnt=0;
12     for(int i=n-1;i>=0;i--)
13         rev[cnt++]=str[i];
14 }
15 int main()
16 {
17     int n;
18     scanf("%d",&n);
19     scanf("%s",str);
20     get_rev(n,str);
21     //cout<<str<<endl<<rev<<endl;
22     memset(dp,0,sizeof(dp));
23 
24     for(int i=1;i<=n;i++){
25         //dp[i][j]=max(dp[i-1][j],dp[i+1][j]);
26         for(int j=1;j<=n;j++){
27             if(str[i-1]==rev[j-1]) dp[i][j]=dp[i-1][j-1]+1;
28             else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
29         }
30     }
31 
32     printf("%d
",n-dp[n][n]);
33     return 0;
34 }
原文地址:https://www.cnblogs.com/CSU3901130321/p/3902785.html