字符串对称处理
问题:要 求对任意一个字符串,通过加入若干字符,使其对称。如Ab3bd 插入两个字符后可以变成dAb3bAd或Adb3bdA,但插入两个字符以下却无法完成对称性处理。请求出需要插入的最少字符数。
引入Cost[ i][j]表示将串S从第j位开始长度为i的子串sub处理成对称的最小插入字符数,
则按子串sub的长度从大到小依次进行递推求:
cost[i-2][j+1] 若st[j]=st[i+j-1]
Cost[i][j]=
min{cost[i-1][j]+1,cost[i-1][j+1]+1}
若st[j]<>st[i+j-1]; 2=<i<=n,1<j<=n-i(注意j是数组的下标,从0开始)
i=0或i=1时cost取值均为0。
#include <stdio.h>
#define MAX 100
int cost[MAX+1][MAX];
int compute(char *s ,int n)
{
int i,j;
for(int k=0;k<n;k++)
cost[0][k]=0;
for(int l=0;l<n;l++)cost[1][l]=0;
for( i=2;i<=n;i++)
{
for(j=0;j<=n-i;j++)
{
if(s[j]==s[j+i-1])
cost[i][j]=cost[i-2][j+1];
else
{
if(cost[i-1][j]>=cost[i-1][j+1])
cost[i][j]=cost[i-1][j+1]+1;
else cost[i][j]=cost[i-1][j]+1;
}
}
}
return cost[n][0];
}
void main()
{
int n,m=0;
char c;
printf("please input the number of chars:");
scanf("%d",&n);
char *s=new char(n+1);
printf("please input the String end with #:");
while((c=getchar())!='#')
s[m++]=c;
int d=compute(s,n);
printf("/n使字符串变成对称至少插入的字符个数为:%d",d);
}