LeetCode5. Longest Palindromic Substring(中心扩散法)

一、问题描述

Given a string s, find the longest palindromic substring(最长回文字符串) in s. You may assume that the maximum length of s is 1000.

Example:

Input: “babad”

Output: “bab”

Note: “aba” is also a valid answer.

Example:

Input: “cbbd”

Output: “bb”


二、思路(中心扩散法Spread From Center)

  1. 用for循环遍历字符串的每一个字符,每找到一个字符就以此为中心,往两边拓展,看左右字符串是否相等。
  2. 但是回文有两种类型,一种为奇数,一种偶数,如下:
    奇数回文:aba
    偶数回文:abba
    所以处理时,需考虑此2种情况。
  3. 算法理解起来很简单,关键是思路。
  4. 算法时间效率为O(n^2)

三、程序示例

C#版本

class Program
{
    //中心扩散法
    public static string LongestPalindrome(string s)
    {
        if (s.Length<2)
        {
            return s;
        }

        int start = 0;
        int end = 0;
        int maxLen = 0;

        for (int i = 0; i < s.Length; i++)
        {
            //针对bab情形
            int m = i;
            int n = i;
            while (((m-1)>=0) && (n+1if (s[m-1] == s[n+1])
                {
                    m--;
                    n++;
                }
                else
                {
                    break;
                }
            }

            if (maxLen < n-m+1)
            {
                start = m;
                end = n;
                maxLen = n - m + 1;
            }

            //针对baab情形
            m = i;
            n = i+1;
            while (m>=0 && nif (s[m]==s[n])
                {
                    m--;
                    n++;
                }
                else
                {
                    break;
                }
            }

            if (m!=i && maxLen < (n - 1 -(m+1) + 1))
            {
                start = m + 1;
                end = n - 1;
                maxLen = end - start + 1;
            }
        }

        return s.Substring(start, maxLen);
    }

    static void Main(string[] args)
    {
        //string str = "abaaba";
        //string str = "eabcb";
        string str = "ccc";
        //string str = "cbbd";
        string result = LongestPalindrome(str);
    }
}

END.

你可能感兴趣的:(LeetCode,LeetCode,算法,笔试,中心扩散法)