目录
频道首页
算法进修——力扣0005最长回文子串
收藏
0
Aubyn 最近修改于 2023-11-01 21:53:37

最长回文子串

难度:中等

题目描述

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

示例1

输入:s = "babad" 输出:"bab"

示例2

输入:s = "cbbd" 输出:"bb"

题解

滑动窗口法,遍历每一个字符,每次遍历用leftright来记录当前窗口然后向右滑动知道超出数组或者和下标数不相等就停止,最后向两边滑动窗口判断回文,直到不相等或超过边界。记录最长的子串

想法代码

class Solution
{
    public static void Main(String[] args)
    {
        string s = "babad";
        Console.WriteLine(LongestPaildrome(s));
    }

    public static string LongestPaildrome(string s)
    {
        int left;
        int right;
        int index = 0;
        int count;
        int max = 0;
        int resultleft = 0;

        while (index < s.Length)
        {
            right = left = index;
            while (true)
            {
                right++;
                if (right >= s.Length || s[right] != s[left])
                {
                    right--;
                    break;
                }
            }
            while (true)
            {
                right++;
                left--;
                if (left < 0 || right >= s.Length || s[left] != s[right])
                {
                    left++;
                    right--;
                    break;
                }
            }

            count = right - left + 1;
            if (max < count)
            {
                max = count;
                resultleft = left;
            }

            index++;
        }
        return s.Substring(resultleft, max);
    }
}
内容大纲
批注笔记
算法进修——力扣0005最长回文子串
ArticleBot
z
z
z
z
主页
会议室
Git管理
文章
云文档
看板