leetcode 5 查找最长的回文子串

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

示例 1:

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

示例 2:

输入: "cbbd"
输出: "bb"

public static  string LongestPalindrome(string s)
        {
            string result = "";
            if(string.IsNullOrWhiteSpace(s))
            {
                return s;
            }

            if(s.Length == 1 || s.Length > 1000)
            {
                return s;
            }

            else if(s.Length == 2)
            {
                if(IsHuiZiChuan(s))
                {
                    return s;
                }
                else
                {
                    return s[0].ToString();
                }
            }

            List<string> listTmp = new List<string>();
            int maxCount = 0;
            for(int i=0;i<s.Length -1;i++)
            {
                string si = s[i].ToString();
                for (int j=i+1;j<s.Length;j++)
                {
                    si += s[j];
                    if(IsHuiZiChuan(si))
                    {
                        listTmp.Add(si);
                        if(si.Length > maxCount)
                        {
                            maxCount = si.Length;
                            result = si;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if(result == "")
            {
                return s[0].ToString();
            }

             
            
            return result;
        }

        public static bool IsHuiZiChuan(string str)
        {
            if(str.Length == 1)
            {
                return true;
            }

            for (int i = 0; i < (str.Length / 2); i++)
            {
                if(str[i] != str[str.Length - i -1])
                {
                    return false;
                }

            }
            return true;

           
        }

代码可以执行,但是时间和空间复杂度不佳,还需要进一步优化。

posted @ 2019-02-28 11:32  雨飞  阅读(162)  评论(0编辑  收藏  举报