Description
By definition palindrome is a string which is not changed when reversed. "MADAM" is a nice example of palindrome. It is an easy job to test whether a given string is a palindrome or not. But it may not be so easy to generate a palindrome.
Here we will make a palindrome generator which will take an input string and return a palindrome. You can easily verify that for a string of length n, no more than (n - 1) characters are required to make it a palindrome. Consider "abcd" and its palindrome "abcdcba" or "abc" and its palindrome"abcba". But life is not so easy for programmers!! We always want optimal cost. And you have to find the minimum number of characters required to make a given string to a palindrome if you are only allowed to insert characters at any position of the string.
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains a string of lowercase letters denoting the string for which we want to generate a palindrome. You may safely assume that the length of the string will be positive and no more than 100.
Output
For each case, print the case number and the minimum number of characters required to make string to a palindrome.
Sample Input
6
abcd
aaaa
abc
aab
abababaabababa
pqrsabcdpqrs
Sample Output
Case 1: 3
Case 2: 0
Case 3: 2
Case 4: 1
Case 5: 0
Case 6: 9
经典的用动态规划解决回文字符串问题,思维价值很大
用动态规划的思想来求解,首先设置dp[i][j]表示第i个字符到第j个字符形成回文串最少需要插入的字符个数。
接下来状态转移,如果第i个字符和第j个字符相同,那么dp[i][j]=dp[i+1][j-1],此时不需要插入任何字符。
如果第i个字符和第j个字符不相同,那么dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1,方程的含义为比较第i+1个字符到第j个字符之间形成回文串需要插入最少字符个数与第i个字符到第j-1个字符之间形成回文串需要插入最少字符的个数,如果dp[i+1][j]小于dp[i][j-1],此时可以在第j个字符后面插入一个和s[i]相同的字符用来形成回文串,同理。如果dp[i][j-1]小于或者等于dp[i+1][j],可以在i的前面插入一个和s[j]相同的字符串。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 110;
char str[N];
int dp[N][N];
int main()
{
int t, ncase=1;
scanf("%d", &t);
while(t--)
{
scanf("%s",str);
int len=strlen(str);
memset(dp,0,sizeof(dp));
int j;
for(int l=1; l<len; l++)
{
for(int i=0; i+l<len; i++)
{
j=i+l;
if(l==1)
{
if(str[i]==str[j])
{
dp[i][j]=0;
}
else
{
dp[i][j]=1;
}
}
else if(str[i]==str[j])
{
dp[i][j]=dp[i+1][j-1];
}
else
{
dp[i][j]=min(dp[i][j-1],dp[i+1][j])+1;
}
}
}
printf("Case %d: %d\n",ncase++,dp[0][len-1]);
}
return 0;
}