LeetCode-C#-0005.最长回文子串

0.声明

该题目来源于LeetCode
如有侵权,立马删除。
解法不唯一,如有新解法可一同讨论。

1.题目

0005最长回文子串
给你一个字符串s,找到s中最长的回文子串。
如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。

示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。

示例 2:
输入:s = “cbbd”
输出:“bb”

提示:
1 <= s.length <= 1000
s 仅由数字和英文字母组成

2.代码

namespace LeetCode_0005最长回文子串
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string s = "babad";
            LeetCode_LongestPalindrome llp = new LeetCode_LongestPalindrome();
            string s_Result = llp.LongestPalindrome(s);

            Console.WriteLine(s_Result);
            Console.ReadKey();
        }
    }


    class LeetCode_LongestPalindrome
    {
        public string LongestPalindrome(string s)
        {
            int n = s.Length;
            bool[,] P = new bool[n, n];
            string s_Rsult = "";

            //遍历所有的长度
            for (int i = 1; i <= n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    int i_End = j + i - 1;
                    if (i_End >= n)
                        break;

                    //长度为1和2 单独判断
                    P[j, i_End] = (i == 1 || i == 2 || P[j + 1, i_End - 1]) && s[j] == s[i_End];
                    if (P[j, i_End] && i > s_Rsult.Length)
                        s_Rsult = s.Substring(j, i);
                }
            }

            return s_Rsult;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值