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
解题思路:这是一个回文串问题,与之前写的回文串问题差不多,只有一两个地方不同。这里输入的字符串数目是有限制的,字符串的长度也需要求出来,在题中我的字符串是从a[1]开始存的,所以用strlen函数求字符串长度时需要从a[1]开始求,所以要写成strlen(a+1);的这种形式。
程序代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
short dp[105][105];
char a[105];
char b[105];
int main(){
int n,m,i,j,t=0;
scanf("%d",&n);
while(n--){
t++;
scanf("%s",a+1);
strcpy(b,a+1);
m=strlen(a+1);
for( i=0;i<=m;i++){
dp[i][m]=0;
}
for( j=0;j<=m;j++){
dp[0][j]=0;
}
for( i=1;i<=m;i++){
for( j=m-1;j>=0;j--){
if(a[i]==b[j]){
dp[i][j]=dp[i-1][j+1]+1;
}
else{
dp[i][j]=((dp[i-1][j])>(dp[i][j+1]))?(dp[i-1][j]):(dp[i][j+1]);
}
}
}
int res=m-dp[m][0];
printf("Case %d: %d
",t,res);
}
return 0;
}