Problem
- Count the number of character replacements necessary to convert an input
String
to a palindrome. - Each character replacement must replace the given character with the character directly before it in the alphabet (sorted A-Z).
- In other words,
D
can only be replaced withC
. - For simplicity, only consider
String
s that are comprised of alphabetic characters.
Inspired by this HackerRank problem.
Example
A
=> already palindromic, so 0 character replacements are necessaryACBD
=>ABBD
=>ABBC
=>ABBB
=>ABBA
, 4 character replacements
Implementation
- The solution is pretty basic, so maybe getting feedback is unnecessary, but is there a better implementation?
public class PalindromeConversionCounter {
public static int count(String s) {
int count = 0;
char[] chars = s.toCharArray();
for (int i = 0; i < Math.ceil(chars.length / 2); i++) {
char currentChar = Character.toLowerCase(chars[i]);
char oppositeChar = Character.toLowerCase(chars[chars.length - 1 - i]);
if (!Character.isAlphabetic(currentChar) || !Character.isAlphabetic(oppositeChar)) {
throw new IllegalArgumentException("String should contain only alphabetic characters");
}
count += Math.abs(currentChar - oppositeChar);
}
return count;
}
}