A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction.
To check whether a word is a palindrome I get th
I was looking for a solution that not only worked for palindromes like...
...but as well for...
Iterative: This has be proven as a good solution.
private boolean isPalindromeIterative(final String string)
{
final char[] characters =
string.replaceAll("[\\W]", "").toLowerCase().toCharArray();
int iteratorLeft = 0;
int iteratorEnd = characters.length - 1;
while (iteratorEnd > iteratorLeft)
{
if (characters[iteratorLeft++] != characters[iteratorEnd--])
{
return false;
}
}
return true;
}
Recursive. I think this solution shouldn't be much worse than the iterative one. Is a little bit crapy we need to extract the cleaning step out of the method to avoid unnecesary procesing.
private boolean isPalindromeRecursive(final String string)
{
final String cleanString = string.replaceAll("[\\W]", "").toLowerCase();
return isPalindromeRecursiveRecursion(cleanString);
}
private boolean isPalindromeRecursiveRecursion(final String cleanString)
{
final int cleanStringLength = cleanString.length();
return cleanStringLength <= 1 || cleanString.charAt(0) ==
cleanString.charAt(cleanStringLength - 1) &&
isPalindromeRecursiveRecursion
(cleanString.substring(1, cleanStringLength - 1));
}
Reversing: This has been proved as a expensive solution.
private boolean isPalindromeReversing(final String string)
{
final String cleanString = string.replaceAll("[\\W]", "").toLowerCase();
return cleanString.equals(new StringBuilder(cleanString).reverse().toString());
}
All the credits to the guys answering in this post and bringing light to the topic.