Simplification time!
if(pal.charAt(0) == pal.charAt(1)) { return true; } return false;
Can become:
return pal.charAt(0) == pal.charAt(1);
if(pal.charAt(0) == pal.charAt(pal.length()-1)) { return isPalidrome(pal.substring(1, pal.length()-1)); } return false;
Can become:
return pal.charAt(0) == pal.charAt(pal.length()-1) && isPalidrome(pal.substring(1, pal.length()-1));
Now, what about an empty string? At the moment, this would cause an exception because the code would run pal.charAt(0)
.
Therefore it would be better to check pal.length() <= 1
first and return true
if that's the case.
You can also remove all else
because you're returning inside all the if
-statements.
After changing the braces style to use {
on the same line instead of it's own line (to adhere to the Java conventions), this leaves us with:
private static boolean isPalindrome(String pal) { if (pal.length() <= 1) { return true; } if (pal.length() == 2) { return pal.charAt(0) == pal.charAt(1); } return pal.charAt(0) == pal.charAt(pal.length() - 1) && isPalidrome(pal.substring(1, pal.length() - 1)); }
Now, even though this can be rewritten using a ternary operator, I wouldn't recommend it because it would end up being quite unreadable. Actually, I'm a bit skeptic already at the last return
line.
Actually, I believe that the if (pal.length() == 2)
check is unnecessary, as that's already covered in the last return statement (it would call the function once more for an empty string, which now returns true).
So if you really want just a one-liner for this:
return pal.length() <= 1 ? true : pal.charAt(0) == pal.charAt(pal.length() - 1) && isPalidrome(pal.substring(1, pal.length() - 1));
Not the prettiest one-liner I've ever seen, but I believe it works. Personally, I'd prefer a non-one-liner for this method. Writing code on one line just because you can isn't always the best option.
Note that this uses the Ternary Operator, which you should read up on to make sure you understand it in case you haven't seen it already.
Edit:
As correctly stated by Josay in the comments below, the ternary operator can be re-written once more using boolean OR:
return pal.length() <= 1 || ( pal.charAt(0) == pal.charAt(pal.length() - 1) && isPalidrome(pal.substring(1, pal.length() - 1)) );
Note however that now I'm adding parenthesis around the last statement, as I don't like mixing ||
with &&
on the same line.
Once again though, consider the readability differences to this line compared to my previous non-one-liner rewrite, or compared to @200_success' answer.