Sharukh Sharukh - 2 months ago 47
Java Question

Finding the lexicographically smallest palindrome

I wrote the following code and outputs also come as required. However when I submit my code in a website, it always ends up showing that the answer is wrong.
Can anyone find any possible mistakes which are responsible for the errors(which I can't see any).

The task is to convert a given string into a palindrome(IF POSSIBLE). The input format is

a.bc
.aacc


The outputs for the above are -1, two times as the strings can't be converted to palindrome, no matter what you keep in the place of
.


Here is my code:

import java.util.*;
class m
{
static int p,o,k,m;
public static void main(String args[])
{
String a[] = new String[500];
int e[] = new int[500];
int i,j;
m o = new m();
Scanner s = new Scanner(System.in);

int n = s.nextInt();

for(i=0;i!=n;i++)
{
a[i] = s.next();

}

//FOR CHECKING NUMBER OF PAIRS
for(i = 0 ; i < n ; i++)
{
p=0;
for(j = 0 ; j < a[i].length() ; j++)
{
if(a[i].charAt(j) == a[i].charAt(a[i].length() - 1 - j))
{
++p;
}
}
e[i] = p;
}


//IF STRING LENGTH IS EVEN

for(i = 0 ; i < n ; i++)
{
for(j = 0 ; j < a[i].length() ; j++)
{

if(a[i].length()%2 == 0)
{
if(e[i] == (a[i].length() - 2))
{
String h = a[i].replace('.',a[i].charAt(a[i].length() - 1 - a[i].indexOf('.')));
System.out.println(h);
break;
}
else
{
System.out.println("-1");
break;
}
}
//IF STRING LENGTH IS ODD
else
{
if(a[i].indexOf('.') == (((a[i].length() + 1 ) / 2 ) - 1))
{
if(e[i] == (a[i].length() ))
{
String g = a[i].replace('.','a');
System.out.println(g);
break;
}

else
{
System.out.println("-1");
break;
}
}

else if(e[i] == (a[i].length() - 2))
{
String q = a[i].replace('.',a[i].charAt(a[i].length() - a[i].indexOf('.') - 1));
System.out.println(q);
break;
}

else
{
System.out.println("-1");
break;
}
}
}
}

Answer

When I run your code, it seems to work as expected on input containing exactly 1 dot. With no dots (e.g., abba) or more than one dot (ab..) it seems to print -1 always. I cannot tell whether this is as expected (as your web site expects it!). It’s my best guess at what could be wrong.

If you require further help. I believe we need a more precise problem statement, more precise requirements for your program.

Comments