Longest palindrome



Problem to find which substring has the longest palindrome.



Example-1:


Input    : s = "xbbabby"
Output   : "bbabb"  
Explain  : "bbabb" is a longest palindrome in given String.


Example-2:


Input    : s = "tomorrow"
Output   : "orro" 
Explain  : "orro" is a longest palindrome in given String.   







Solution




public class Main
{
    public static void main(String [] args)
    {
        String s = "tomorrow";

        int start = 0, end = 0, left = 0,right = 0;

        boolean f = true;

        for(int i=0;i<s.length();i++)
        {   
            left = i-1;

            right = i+1;

            f = true;

            while(right!=s.length()&&s.charAt(i)==s.charAt(right))   
            {
                right++;
            }

            while(f)
            {
                if(left!=-1&&right!=s.length()&&s.charAt(left)==s.charAt(right))
                {
                    left--;
                    right++;
                }
                else
                {
                    f=false;
                }
            }

            if(end-start<right-left)
            {
                start=left;
                end=right;
            }

        } 
        
        System.out.print(s.substring(start+1,end));
    }
}




Output



orro