0004 最长回文子串

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba"也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"
public class Solution {
    public string LongestPalindrome(string s) {
        List<Section> sections = new List<Section>();
        if(s.Length == 1 || s.Length == 0)
        {
            return s.Length == 1 ? s[0].ToString() : "";
        }
        bool bend = false;
        for(int i=0; i<s.Length; i++)
        {
            if (bend)
            {
                break;
            }
            for(int j=s.Length-1; j>i; j--)
            {
                if (bend)
                {
                    break;
                }
                if (s[j] == s[i])
                {
                    bool flag = true;
                    if((j-i) == 1 || (j-i) == 2)
                    {
                        Section section = new Section();
                        section.start = i;
                        section.end = j;
                        sections.Add(section);
                    }
                    else
                    {
                        for (int k = 1; k <= (i + j) / 2 - i; k++)
                        {
                            if (s[i + k] != s[j - k])
                            {
                                flag = false;
                                break;
                            }
                        }
                        if (flag)
                        {
                            Section section = new Section();
                            section.start = i;
                            section.end = j;
                            sections.Add(section);
                            if(j-i+1 >= s.Length)
                            {
                                bend = true;
                            }
                        }
                    }
                        
                }
            }
        }
        if(sections.Count == 0)
        {
            return s[0].ToString();
        }
        int max = sections[0].end - sections[0].start, pos = 0;
        for(int i=1; i<sections.Count; i++)
        {
            if((sections[i].end - sections[i].start) > max)
            {
                max = sections[i].end - sections[i].start;
                pos = i;
            }
        }
        return s.Substring(sections[pos].start, sections[pos].end - sections[pos].start + 1);
    }
    
    class Section
    {
        public int start;
        public int end;
    }
}
原文地址:https://www.cnblogs.com/lvniao/p/9402554.html