Saturday, 16 September 2017

Write a function to find out longest palindrome in a given string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestAlgo
{
    class Program
    {
        static void Main(string[] args)
        {

            
            string palindrome = Console.ReadLine();
            //string palindrome = "HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE";
            LognestPailindrome longP = new LognestPailindrome();
             Console.WriteLine(longP.FindLongPalindrome(palindrome));
             Console.WriteLine("Counter = " +longP.counter +" and string lenth = " + palindrome.Length  );
             
             Console.ReadLine();
        }
    }
}

----------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestAlgo
{
  public  class LognestPailindrome
    {
      public  int counter = 0;
      public bool IsPalindrome( string str)
      {
          int len=0;
          if (str.Length == 1)
              len = 1;
          else
           len = str.Length / 2;
          int j=str.Length;
          bool isP = true;
          for (int i = 0; i < len; i++)
          {
              if (str.Substring(i, 1) != str.Substring(j-1, 1))
              {
                  isP = false;
                  break;
              }
              j--;
              counter++;
          }
          return isP;
      }

      public string FindLongPalindrome(string str)
      {
          string longStr = "";
          bool islong = false;
          for (int i = 0; i < str.Length; i++)
          {
              string strL = "";
              for (int j = i; j < str.Length; j++)
              {
                  strL = strL + str.Substring(j, 1);
                  if (IsPalindrome(strL))
                  {
                      if (strL.Length > longStr.Length)
                      {
                          longStr = strL;
                          if (longStr.Length > (str.Length - j))
                          {
                              islong = true;
                              break;
                          }
                      }
                  }
                  if (islong)
                      break;
                  counter++;
              }
          }

          return longStr;
      }


    }
}

No comments:

Post a Comment