Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created July 23, 2013 05:22
Show Gist options
  • Select an option

  • Save riyadparvez/6060040 to your computer and use it in GitHub Desktop.

Select an option

Save riyadparvez/6060040 to your computer and use it in GitHub Desktop.
Finds longest palindrome in a string in O(n*n) time and O(1) space.
private static string Expand(string str, int c1, int c2)
{
int left = c1;
int right = c2;
while (left >= 0 && right < str.Length && str[left] == str[right])
{
left--;
right++;
}
return str.Substring(left+1, right-left-1);
}
public static string LongestPalindrome(string str)
{
var chars = str.ToCharArray();
var dp = new bool[chars.Length, chars.Length];
string longest;
for (int i = 0; i < str.Length-1; i++)
{
string str1 = Expand(str, i, i);
if(str1.Length >= longest.Length)
{
longest = str1;
}
string str2 = Expand(str, i, i+1);
if (str2.Length >= longest.Length)
{
longest = str2;
}
}
return longest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment