Leetcode5. Longest palindromic substring (central diffusion method)

Posted by Horatiu on Thu, 02 Apr 2020 09:18:01 +0200

1, Problem description

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"

2, Ideas (Spread From Center)

  1. Use the for loop to iterate through each character of the string. Each character found is centered on it and extended to both sides to see whether the left and right strings are equal.
  2. But there are two types of palindrome, one is odd and the other is even, as follows:
    Odd palindrome: aba
    Even palindrome: abba
    Therefore, these two situations need to be considered when handling.
  3. The algorithm is easy to understand, the key is the idea.
  4. Algorithm time efficiency is O(n^2)

3, Program example

C# version

class Program
{
    //Central diffusion method
    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++)
        {
            //For bab
            int m = i;
            int n = i;
            while (((m-1)>=0) && (n+1<s.Length))
            {
                if (s[m-1] == s[n+1])
                {
                    m--;
                    n++;
                }
                else
                {
                    break;
                }
            }

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

            //In the case of baab
            m = i;
            n = i+1;
            while (m>=0 && n<s.Length)
            {
                if (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.