Problem Statement: You are given an input string A[1…n].Of all the sub-strings of A,find the longest sub-string ‘s’ such that ‘s’ appears both forward and backward in A. The forward and backward sub-strings should not overlap. For example, for the input string “SAWMWASING”, the output should be “SAW”. For the input string “DYNAMICPROGRAMANYTIMES”, the output should be “YNAM”.
Solution:
import java.util.*;
class bkfw
{
public static void main(String args[])
{
String str,s1,s2;
int n,i,j,k,a=0,index=0;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a string”);
str=sc.nextLine();
n=str.length();
StringBuffer st= new StringBuffer(str);
String s[]=new String[20];
for(i=0;i<Math.round((float)n/2);i++) //rounding off for odd no of alphabets in the string
for(j=2;j<Math.round((float)n/2);j++) //j defines length of string,minimum length of string is taken as 2
for(k=0;k+j<st.length();k++)
{
s1=str.substring(i,i+j);
st.replace(0,st.length(),str.substring(i+j));
st.reverse(); //only reversing rest of the string to avoid overlapping
s2=st.substring(k,k+j);
if (s1.equals(s2))
{
s[a]=s1;
a++;
}
}
if(a>0)
{
n=s[0].length();
for(i=0;i<a;i++)
if(n<s[i].length())
{
n=s[i].length();
index=i;
}
System.out.println(s[index]+” is the longest substring that repeats backwards and forwards”);
}
else
System.out.println(“no such substring exists that repeats backwards and forwards”);
}
}