【编程题】构造回文

原题出处:牛客网-腾讯2017暑期实习生编程题

构造回文
时间限制:1秒

空间限制:32768K

给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
输出需要删除的字符个数。

输入描述:

输入数据有多组,每组包含一个字符串s,且保证:1<=s.length<=1000.

输出描述:

对于每组数据,输出一个整数,代表最少需要删除的字符个数。

输入例子1:
abcda
google

输出例子1:
2
2

解题思路:
 回文的特性:翻转等于它本身,因此我们只需要找出原串与反串(原串翻转后的串)的最长公共子序列(LCS)的长度,然后用原串长度减去LCS即可得出结果。
 LCS的具体讲解可参考:
 Running07-动态规划 最长公共子序列 过程图解

以下为题解:

using System;

public class Program
{
  // LCS
    static int LCS(string str1, string str2)
    {
        int[,] res = new int[str1.Length+1, str2.Length+1];
        for(int i=0; i<str1.Length; i++)
        {
            res[i,0] = 0;
        }
        for(int j=0; j<str2.Length; j++)
        {
            res[0,j] = 0;   
        }

        for(int i=1; i<=str1.Length; i++)
        {
            for(int j=1; j<=str2.Length; j++)
            {
                if(str1[i-1] == str2[j-1])
                    res[i,j] = res[i-1,j-1] + 1;
                else
                    res[i,j] = Math.Max(res[i-1,j],res[i,j-1]);
            }
        }

        return res[str1.Length, str2.Length];
    }

    // Calculate how many char we need to delete.
    static int DelCount(string str1)
    {
      // Reverse the str.
        char[] cStr = str1.ToCharArray();
        Array.Reverse(cStr);
        string str2 = new string(cStr);

        int commonLen = LCS(str1, str2);

        return str1.Length - commonLen;
    }

    public static void Main(string[] args)
    {
        string str;
        while((str=Console.ReadLine()) != null)
        {
            int result = DelCount(str);
            Console.WriteLine(result);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值