Determining the longest palindrome in a given string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Determining the longest palindrome
            string str = "forgeeksskeegfor";
            int flag = 0;
            for (int i = str.Length; i >= 1; i--) //string length
            {
                for (int j = 0; j <= str.Length - i; j++) //start position
                {
                    string tempStr = "";
                    for (int k = j; k < j + i; k++)
                    {
                        tempStr = tempStr + str[k];
                    }
                    if (IsPalindrome(tempStr))
                    {
                        Console.WriteLine("Longest palindrome is: " + tempStr);
                        flag = -1;
                        break;
                    }
                }
                if (flag == -1)
                {
                    break;
                }
            }
            if (flag == 0)
            {
                Console.WriteLine("No palindrome found");
            }
        }
        
        public static bool IsPalindrome(string text) 
        { 
            return text == new String(text.Reverse().ToArray());
        } 
    }
}

Output
======
Longest palindrome is: geeksskeeg
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

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