Updated on January 06 2020 • Martin Shishkov

Coding Challenge 'Longest Palindromic Substring' - LeetCode

Here's my take on the Longest Palindrome Substring coding challenge from LeetCode

Longest Palindrome Substring Problem

My first quick attempt at this is a pretty naive solution, here is the C# code:

public string LongestPalindrome(string s) {
    if (string.IsNullOrWhiteSpace(s))
            return string.Empty;

    if (IsPalindrome(s))
        return s;

    string result = s[0].ToString();

    for(var i = 0; i < s.Length; i++)
    {
        var minPalindromeLength = result.Length + 1;
        for(var j = minPalindromeLength; j <= s.Length - i; j++)
        {
            var substr = s.Substring(i, j);
            if (substr.Length > result.Length && IsPalindrome(substr))
            {
                result = substr;
            }
        }
    }

    return result;
}

private bool IsPalindrome(string s)
{
    var iterations = s.Length / 2;

    for (var i = 0; i < iterations; i++)
    {
        var endIndex = s.Length - i - 1;
        if (s[i] != s[endIndex])
            return false;
    }
    
    return true;
}

Unfortunately this does not pass all the tests and I get 'Time Limit Exceeded' Status.

However, it does receive 73 passed tests out of 103 in total.

UPDATE:

The solution now passes the tests without any change. However the results are not that exciting:

Runtime: 1720 ms, faster than 5.06% of C# online submissions for Longest Palindromic Substring. Memory Usage: 26.5 MB, less than 32.00% of C# online submissions for Longest Palindromic Substring.