Code style
- Definitely make the helper methods private;
- There is no need to specify the class name when calling a static method in the same call. Instead of
AlphanumericPalindromeValidator.isNumericCharacterPair(), just callisNumericCharacterPair(); - Do a static import of the static methods of
Character; - There is no need for the variables
oppositeCharacterandcharacter. Only keep them if it helps you make the code easier to read. - it's possible to make the inner while loop a one liner with a
for, but I actually think thewhilebetter expresses what is the intent in this case.
If condition
I don't see the point of the first check: i < j. At ths point you know that i<=j. If i == j, the comparison will succeed. This is the case of palindromes with an odd length.
You don't need to check if the char is alphabetic to use Character.toLowerCase(). The method will simply return the same char if there is no mapping to lower case for a given char.
You can also use Character.isLetterOrDigit instead of your isAlphanumeric, unless you care about the subtle differences between "alphatetic" and "letter".
Resulting while loop
Suggested solution
No helper methods are needed.
public static boolean isValid(String value) {
char[] chars = value.toCharArray();
int i = 0;
int j = value.length() - 1;
while (i < j) {
while (!isLetterOrDigit(chars[i]) && i < j) {
i++;
}
while (!isLetterOrDigit(chars[j]) && i < j) {
j--;
}
if (Character.toLowerCase(chars[i]) != toLowerCase(chars[j])) {
return false;
}
i++;
j--;
}
return true;
}