This question is asked in the Programming Test Round in Nagarro. This question firstly seems quiet simple but it is a little tricky.
The requirements are – we have to find longest palindrome in a string. In the below solution , we can achieve longest/small palindrome, number of palindromes , length of palindrome.
using System; namespace PalindromeDemo { class Program { static int count = 0; static string lng = ""; static void Main(string[] args) { string name = "ABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOOD"; Method1(name); Console.WriteLine("Longest : " + lng); Console.WriteLine("Length : " + count); Console.Read(); } public static void Method1(string name) { Console.WriteLine("Name : " + name); int length = name.Length; for (int i = 0; i <= length - 2; i++) { int j = 0; for ( j = i + 1; j <= length - 1; j++) { if (name[i] == name[j]) { if (i == 0) Method2(name.Substring(i, j + 1)); else Method2(name.Substring(i, (j - i) + 1)); } } } } public static void Method2(string str) { string rev = ""; for (int i = str.Length - 1; i >= 0; i--) { rev += str[i].ToString(); } if (rev == str) { if (str.Length > count) { lng = str; count = str.Length; } } } } }