RSS

Program to find longest palindrome in string with C#

Tue, Dec 8, 2009

Inverview Tips, Programming, Tutorials

Are you searching for solution for finding longest palindrome in string? If so we’ve something for you. We have following C# example for finding longest palindrome in character array (or string). We’ve two different while loop to find longest palindrome for odd length palindromes and even lenth palindromes.

 /// <summary>
 /// This method finds longest palindrome in a character array.
 /// </summary>
 /// <param name="input">array of characters</param>
public void FindLongestPalindrome(char[] input)
{
	int len;
	int i = 0, j = 0, k = 0, l = 0;
	int lower = 0, upper = 0;
	len = input.Length;
 
	/*Odd length Palindromes*/
	while (i < len && j < len)
	{
		k = i;
		l = j;
		while ((k >= 0 && l < len) && (input[k] == input[l]))
		{
			if ((upper - lower) <= (l - k))
			{
				lower = k;
				upper = l;
			}
			k--;
			l++;
		}
		i++;
		j++;
	}
 
	/*Even length Palindromes*/
	i = 0;
	j = 1;
	while (i < len && j < len)
	{
		k = i;
		l = j;
		while ((k >= 0 && l < len) && (input[k] == input[l]))
		{
			if ((upper - lower) <= (l - k))
			{
				lower = k;
				upper = l;
			}
			k--;
			l++;
		}
		i++;
		j++;
	}
 
	for (i = lower; i <= upper; i++)
	{
		Console.Write(input[i]);
	}
	Console.WriteLine();
}
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

, ,

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.