Mi primer código de golf.
Java. ~ 1200 caracteres en las funciones principales (y secundarias). Sí bebé.
Clase superior y uso:
public class ElimOneCharForPalindrome {
public static final void main(String[] ignored) {
System.out.println(getEliminateForPalindromeIndex("racercar"));
System.out.println(getEliminateForPalindromeIndex("racecar"));
}
La función principal:
public static final int getEliminateForPalindromeIndex(String oneCharAway_fromPalindrome) {
for(int i = 0; i < oneCharAway_fromPalindrome.length(); i++) {
String strMinus1Char = oneCharAway_fromPalindrome.substring(0, i) + oneCharAway_fromPalindrome.substring(i + 1);
String half1 = getFirstHalf(strMinus1Char);
String half2Reversed = getSecondHalfReversed(strMinus1Char);
if(half1.length() != half2Reversed.length()) {
//One half is exactly one character longer
if(half1.length() > half2Reversed.length()) {
half1 = half1.substring(0, (half1.length() - 1));
} else {
half2Reversed = half2Reversed.substring(0, (half2Reversed.length() - 1));
}
}
//System.out.println(i + " " + strMinus1Char + " --> " + half1 + " / " + half2Reversed + " (minus the singular [non-mirrored] character in the middle, if any)");
if(half1.equals(half2Reversed)) {
return i;
}
}
return -1;
}
Subfunciones:
public static final String getFirstHalf(String whole_word) {
return whole_word.substring(0, whole_word.length() / 2);
}
public static final String getSecondHalfReversed(String whole_word) {
return new StringBuilder(whole_word.substring(whole_word.length() / 2)).reverse().toString();
}
}
Clase completa:
public class ElimOneCharForPalindrome {
public static final void main(String[] ignored) {
System.out.println(getEliminateForPalindromeIndex("racercar"));
System.out.println(getEliminateForPalindromeIndex("racecar"));
}
public static final int getEliminateForPalindromeIndex(String oneCharAway_fromPalindrome) {
for(int i = 0; i < oneCharAway_fromPalindrome.length(); i++) {
String strMinus1Char = oneCharAway_fromPalindrome.substring(0, i) + oneCharAway_fromPalindrome.substring(i + 1);
String half1 = getFirstHalf(strMinus1Char);
String half2Reversed = getSecondHalfReversed(strMinus1Char);
if(half1.length() != half2Reversed.length()) {
//One half is exactly one character longer
if(half1.length() > half2Reversed.length()) {
half1 = half1.substring(0, (half1.length() - 1));
} else {
half2Reversed = half2Reversed.substring(0, (half2Reversed.length() - 1));
}
}
//System.out.println(i + " " + strMinus1Char + " --> " + half1 + " / " + half2Reversed + " (minus the singular [non-mirrored] character in the middle, if any)");
if(half1.equals(half2Reversed)) {
return i;
}
}
return -1;
}
public static final String getFirstHalf(String whole_word) {
return whole_word.substring(0, whole_word.length() / 2);
}
public static final String getSecondHalfReversed(String whole_word) {
return new StringBuilder(whole_word.substring(whole_word.length() / 2)).reverse().toString();
}
}