This program takes lines of input. The first line is an int
specifying how many further lines will be input. For the following lines (comprised of characters a-z), it will be determined whether removing one character from the line can result in the line being a palindrome.
I know this can be substantially improved, but I don't know how. Could I somehow capitalize on the fact that only characters a-z are used?
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int cases = Integer.parseInt(br.readLine());
for (int i = 0; i < cases; i++) {
System.out.println(canBePalindrome(br.readLine()) ? "YES" : "NO");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean canBePalindrome(String line) {
if (line.length() <= 1) {
return false;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < line.length(); i++) {
if (isPalindrome(sb.append(line).deleteCharAt(i).toString())) {
return true;
}
sb.setLength(0);
}
return false;
}
private static boolean isPalindrome(String line) {
return line.equals(new StringBuilder(line).reverse().toString());
}
}
isPalindrome
. What exactly are you trying to accomplish? Also, any string of length 1 is the same forward and backward, hence, a palindrome. \$\endgroup\$canBePalindrome()
checks whether removing one character from the String can create a palindrome.isPalindrome
checks if a String is a palindrome. Admittedly, the method name isn't the best, but everything should be obvious from the specs I provided. \$\endgroup\$