I was looking for a solution that not only worked for palindromes like ...
... but also for ...
- "Man, plan, channel, Panama!"
- "Was it the car or the cat I saw?"
- No x at Nixon
Iterative : This has been 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 should not be much worse than iterative. We need a little therapy in order to extract the cleansing step from the method in order to avoid an unnecessary process.
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)); }
Reverse : This has been proven as an expensive solution.
private boolean isPalindromeReversing(final String string) { final String cleanString = string.replaceAll("[\\W]", "").toLowerCase(); return cleanString.equals(new StringBuilder(cleanString).reverse().toString()); }
All loans to the guys who answer this post and bring light to the topic.
Sotti Oct 24 '16 at 15:51 2016-10-24 15:51
source share