Search code examples
c#algorithmsubstring

Why doesn't my code always detect palindromes in substrings correctly?


I am working with an algorithm that should find longest palindrome within a given string. So far, I've done some R & D and got a solution that's almost similar to mine. After doing some tweaks, got the following so far:

public static string Find_LongestPalindrome(string s)
{
    var charsArray = s.ToCharArray();
    var boolArr = new bool[charsArray.Length, charsArray.Length];
    
    int longestStart = 0;
    int maxLength = 1;
    
    //By default, the matching array indexes are kept true for tracking similar characters
    for (int i = 0; i < charsArray.Length; i++)
    {
        boolArr[i, i] = true;
    }

    for (int i = 0; i < charsArray.Length - 1; i++)
    {
        //This checks if there are matching characters and their length in the given string
        if (charsArray[i] == charsArray[i + 1])
        {
            boolArr[i, i + 1] = true;
            longestStart = i;
            maxLength = 2;
        }
    }

    //Keeps track of the character length that has length of two in a substring
    for (int length = 2; length <= charsArray.Length; length++)
    {
        for (int i = 0; i < charsArray.Length - length + 1; i++)
        {
            int j = i + length - 1;
            if (charsArray[i] == charsArray[j] && boolArr[i + 1, j - 1])
            {
                boolArr[i, j] = true;
                if (maxLength < (j - i))
                {
                    maxLength = j - i;
                    longestStart = i;
                }
            }
        }
    }

    //Returns the substring that's found
    if (s.Length == longestStart + (maxLength + 1))
    {
        return s.Substring(longestStart, maxLength + 1);
    }
    else
    {
        return s = "none";
    }
}

Here's the fiddle that I did so far: Longest Palindrome

The above solution worked, but unable to get the desired solution for one of the following input:

(The logic here is to find the longest palindrome in a given string that has at least length of two and greater)

Input 1: hellosmithsannas Output 1: sannas
Input 2: hellosannasmith Output 2: sannas
Input 3: abcdefgg Output 3: none

In my case, the code I tried is able to run for the inputs 1 and 3. But for the input 2, I am getting none, though it should return sannas as the minimum length is two and the longest string is found in a pattern. Is there anything that I missed here?


Solution

  • if (s.Length == longestStart + (maxLength + 1))
    

    implies that you're only interested in longest palindromes which happen at the end of the string. To consider palindromes in other locations, it should be just:

    if (maxLength > 1)