Skip to content

Instantly share code, notes, and snippets.

@baratgabor
Last active April 28, 2019 14:51
Show Gist options
  • Save baratgabor/9ef7e38cce5a593f0647d89af5551805 to your computer and use it in GitHub Desktop.
Save baratgabor/9ef7e38cce5a593f0647d89af5551805 to your computer and use it in GitHub Desktop.
Compact & naive C# function to get the longest palindromic substrings of a string (i.e. all palindromes excluding overlaps). Time complexity is over quadratic.
// Naive, suboptimal
IEnumerable<string> GetLongestPalindromes(string s)
{
List<string> palindromes = new List<string>();
var len = s.Length;
for (int i = 0; i < len; i++)
{
for (int j = len - 1; j > i; j--)
{
for (int k = 0; true; k++)
{
if (s[i + k] != s[j - k])
break; // Not palindrome
int dist = (j - k) - (i + k);
if (dist <= 1) // Center reached, palindrome found; dist = 0 odd length, dist = 1 even length
{
palindromes.Add(s.Substring(i, j - i + 1));
i = j; // Skip overlapping palindromes
break;
}
}
}
}
return palindromes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment