В качестве альтернативы, рекурсия .
Для всех, кто ищет более короткое рекурсивное решение, проверить, удовлетворяет ли данная строка как палиндром:
private boolean isPalindrome(String s) {
int length = s.length();
if (length < 2) // If the string only has 1 char or is empty
return true;
else {
// Check opposite ends of the string for equality
if (s.charAt(0) != s.charAt(length - 1))
return false;
// Function call for string with the two ends snipped off
else
return isPalindrome(s.substring(1, length - 1));
}
}
ИЛИ даже короче , если вы хотите:
private boolean isPalindrome(String s) {
int length = s.length();
if (length < 2) return true;
return s.charAt(0) != s.charAt(length - 1) ? false :
isPalindrome(s.substring(1, length - 1));
}