3
\$\begingroup\$

I like to request a review of the code below, which is my attempt at answering the question here on LeetCode site. The code passes 43 tests, but it times out on the next one. I copied and ran the test on my machine using visual studio and it seems to give me an answer. I wonder if there is something about the site LeetCode that I should know like a config setting somewhere.

Regardless the problem asks to find the longest palindrome in a string. I have seen and read other posts about this problem, like this one, but I would really like to see answers in C#, because I originally converted my code from Java to C# and found out about the slight difference in the .Substring() method between the two languages. I tried to address it by creating my own method, and wonder if the time out is due to this adjustment.

private static string LongestPalindrome(string s)
{
    int length = s.Length;
    if (s.Length < 2 || s == null)
    {
        return s;
    }
    Boolean[,] isPalindrome = new Boolean[length, length];
    int left = 0;
    int right = 0;
    for (int j = 0; j < length; j++)
    {
        for (int i = 0; i < j; i++)
        {
            Boolean isInnerWordPalindrome = isPalindrome[i + 1, j - 1] || j - i <= 2;
            if (s.ElementAt(i) == s.ElementAt(j) && isInnerWordPalindrome)
            {
                isPalindrome[i, j] = true;
                if (j - i > right - left)
                {
                    left = i;
                    right = j;
                }
            }
        }
    }
    return JavaStyleSubstring(s, left, right + 1);
}

private static string JavaStyleSubstring(string s, int beginIndex, int endIndex)
{
    // simulates Java substring function
    int len = endIndex - beginIndex;
    return s.Substring(beginIndex, len);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.