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