Algorithm
As we know a string can have even & odd length palindrome & any one of them can be larger then other so 1st we will find all odd & even length palindrome of string then we find larger of them.to find odd & even length we will do follow.
for odd length palindrome for each position in string take two variable to store index of element before current index & element after the current index & keep decrementing 1st index & incrementing 2nd index until we won't found any mismatch.save length of maximum odd length palindrome & index of this palindrome. so that in last we just need to compare the maximum odd length palindrome & maximum even lengths palindromic & in last print maximum of them by saving indexes.
class FindAllPalindromes
{
public static void main(String[] args)
{
FindAllPalindromes finder = new FindAllPalindromes();
finder.printAllPalindromes("rorradarpottopradarradar");
}
public void printAllPalindromes(String inputText)
{
int cur1=0,max1=-1,cur2=0,max2=-1,a=0,b=0,c=0,d=0;
if(inputText==null)
{
System.out.println("Input cannot be null!");
return;
}
if(inputText.length()<=2)
{
System.out.println("Minimum three characters should be present");
}
//ODD Occuring Palindromes
int len = inputText.length();
for(int i=1;i<len-1;i++){
for(int j=i-1,k=i+1;j>=0&&k<len;j--,k++){
if(inputText.charAt(j) == inputText.charAt(k))
{
cur1=k+1-j;
if(max1<cur1)
{
max1=cur1; a=j;b=k+1;
//System.out.println(inputText.subSequence(j,k+1));
}
}else{
break;
}
}
}
//EVEN Occuring Palindromes
for(int i=1;i<len-1;i++)
{
for(int j=i,k=i+1;j>=0&&k<len;j--,k++)
{
if(inputText.charAt(j) == inputText.charAt(k))
{
cur2=k+1-j;
if(max2<cur2)
{
max2=cur2;c=j;d=k+1;
//System.out.println(inputText.subSequence(j,k+1));
}
}
else
{
break;
}
}
}
if(max1>max2)System.out.println(inputText.subSequence(a,b));
else System.out.println(inputText.subSequence(c,d));
}
}
Space Complexity O(1)
Run Here https://ideone.com/6Zwes
One More Interesting Explanation I Found Here
http://stevekrenzel.com/articles/longest-palnidrome