I’m trying to find a subpalindrome in Java. But the below code doesn’t provide the correct output.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
String text = in.next();
int start = 0;
int end = 0;
int i = 0;
int j = 0;
while(i <= text.length())
{
j = i+1;
while(j < text.length())
{
if(text.substring(i, j).equals(reverse(text.substring(i, j))))
{
if(j-i > end-start)
{
start = i; end = j;
}
}
j++;
}
i++;
}
System.out.println(start + " : " + end);
}
static String reverse(String s)
{
return new StringBuffer(s).reverse().toString();
}
Sample Output:
apros tda adda
7 : 12
after the ostso
11 : 14
att feref
5 : 8
All of the above are wrong.
PS: I’m aware that this is not an efficient algorithm.
Finally got it working.
Here is a more optimized version. This is based on this