Interview Question Categories

LONGEST PALINDROME IN A STRING

LONGEST PALINDROME IN A STRING

//Idea : Start from a character and explore the chars 
//towards left and right simultaneously.
//Complexiety : O(n2)

namespace LongestPalindrome
{
    class Program
    {
        static string LongestPalindromeImproved(String Str)
        {
            char[] strchr = Str.ToCharArray();
            int left;
            int right;
            int LongestStart = 0;
            int LongestEnd = 0;

            for (int mid = 1; mid < strchr.Length; mid++)
            {
                //To find palindrome of odd length
                left = mid;
                right = mid;

                while (left >= 0 && right < strchr.Length)
                {
                    if (strchr[left] == strchr[right])
                    {
                        if (right - left > LongestEnd - LongestStart)
                        {
                            LongestStart = left;
                            LongestEnd = right;
                        }
                        left--;
                        right++;
                    }
                    else break; 
                }

                //To find palindrome of Even length
                left = mid-1;
                right = mid;

                while (left >= 0 && right < strchr.Length)
                {
                    if (strchr[left] == strchr[right])
                    {
                        if (right - left > LongestEnd - LongestStart)
                        {
                            LongestStart = left;
                            LongestEnd = right;
                        }
                        left--;
                        right++;
                    }
                    else break; 
                }
            }

            if (LongestEnd - LongestStart > 0)
                return new string(strchr, LongestStart, LongestEnd - LongestStart + 1);
            else return "";
        }

        
        static void Main(string[] args)
        {
            String str = "qweert";
            Console.WriteLine(LongestPalindromeImproved(str));
        }
    }
}

No comments:

Post a Comment