Finding the Longest substring in a string that is a palindrome

Hi,

Recently my friend asked me this question so gave it a try and got it. So this is how the code goes:

using System;
using System.Collections.Generic;
using System.Linq;

namespace SubStringPalindrome
{
class Program
{
static int maxLength;

static void Main(string[] args)
{
string inputString = “ootntannanitindennedadinidadeleveledaibohphobiatattarrattat”;
string currentStr = string.Empty;
List<string> listOfPalindromes = new List<string>();

char[] inputStrArr = inputString.ToCharArray();

for (int i = 0; i < inputStrArr.Length; i++)
{
for (int j = i+1; j < inputStrArr.Length; j++)
{
currentStr = inputString.Substring(i, j – i + 1);

if (IsPalindrome(currentStr))
{
listOfPalindromes.Add(currentStr);
if (currentStr.Length > maxLength)
{
maxLength = currentStr.Length;
}
}
}
}

var longest =   from str in listOfPalindromes
where str.Length == maxLength
select str;

foreach (var item in longest)
{
Console.WriteLine(“Longest Palindrome : ” + item.ToString());
}
}

private static bool IsPalindrome(String str)
{
bool IsPalindrome = true;
if (str.Length > 0)
{
for (int i = 0; i < str.Length / 2; i++)
{
if (str.Substring(i, 1) != str.Substring(str.Length – (i + 1), 1))
{
IsPalindrome = false;
}
}
}
else
{
IsPalindrome = false;
}
return IsPalindrome;
}
}
}

Hope this helps!! 🙂

CodeProject
Advertisements

About Amogh Natu

Technology enthusiast, Associate Consultant @ Microsoft, music lover, love my guitar, Microsoft.NET, ASP.NET, C#.NET Professional.
This entry was posted in .NET, C#, CodeProject, General and tagged , , , , , , . Bookmark the permalink.

Your comments or opinions.....

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s