回文字符串

回文字符串

时间限制: 3000 ms  |  内存限制: 65535 KB
    <div class="problem-ins">难度:<span class="editable highlight">4</span></div>      </div>
    <dl class="problem-display">
    <dt>描述 </dt>
    <dd>所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的,比如"aba"。当然,我们给你的问题不会再简单到判断一个字符串是不是回文字符串。现在要求你,给你一个字符串,可在任意位置添加字符,最少再添加几个字符,可以使这个字符串成为回文字符串。</dd>
    <div class="clr"></div>
    <dl class="others">
      <dt>输入</dt>
      <dd>第一行给出整数N(0&lt;N&lt;100)<br>

接下来的N行,每行一个字符串,每个字符串长度不超过1000.

输出
每行输出所需添加的最少字符数

样例输入

1 
Ab3bd


样例输出

2

  </dl>

 //先求出输入字符串的逆序列,求出两个字符串的最长子序列的长度,用总长度减去最长子序列的长度,就是需要补充的字符的个数
#include<stdio.h>
#include<string.h>
int result = 0;
short c[1001][1001];
int max(int a,int b)
{
    return a>b?a:b;
}
void LCS(char *str1,char *str2,int m,int n)
{
    int i,j;
    result = 0;
    for(i = 0;i<=m;i++)
    {
        c[0][i] = 0;
    }
    for(i = 0;i<=n;i++)
    {
        c[i][0] = 0;
    }
    for(i = 1;i<=n;i++)
    {
        for(j = 1;j<=m;j++)
        {
            if(str2[i-1] == str1[j-1])
            {
                c[i][j] = c[i-1][j-1] + 1;
                result = max(c[i][j],result);
            }
            else if(c[i-1][j]>=c[i][j-1])
            {
                c[i][j] = c[i-1][j];
            }
            else
            {
                c[i][j] = c[i][j-1];    
            }
        }   
    } 
}
void reverse(char *str1,char *str2)
{
    int i,k = 0;
    for(i = strlen(str1)-1;i>=0;i--)
        str2[k++] = str1[i];
    str2[k] = '\0';
}
int main()
{
    int n;
    char str1[1000];
    char str2[1000];
    int max;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",str1);
        reverse(str1,str2);
        LCS(str1,str2,strlen(str1),strlen(str2));
        printf("%d\n",strlen(str1)-result);
    }
}                 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值