Java: Exercise - Palindrome
Problem
Write a method which returns true if the string parameter
is a
palindrome. A palindrome is any "word" which is the same
forward and backward, eg, radar, noon, 20011002... The method should return
false if the argument is not a palindrome.
Signature
public static boolean isPalindrome(String s)
Note: This is declared
static because it is doesn't depend on
instance variables from the class it would be defined in.
It only depends on its parameters.
It's declared
public only because
it might be generally useful.
Extensions
You can make clever English palindromes more easily be ignoring spaces,
nonalphabetics, and case (eg, "Drab as a fool, aloof as a bard.").
Example
| Call | Returns | Comments |
isPalindrome("Hello") | false | Not a palindrome. |
isPalindrome("radar") | true | Is a palindrome. |
isPalindrome("Able was I ere I saw elba.") | true | Is a palindrome. |
isPalindrome("A man, a plan, a canal -- Panama!") | false |
Not a palindrome by our definition. See extensions. |
Hints
Index simultaneously from both ends, comparing characters.
Info on palindromes
Check out
www.palindromes.org
if you want to know more about them. This site has lots of
amusing examples, eg, "Doc, note I dissent: a fast never prevents a fatness. I diet on cod."
or "Drat Saddam, a mad dastard!"
Assumptions
Write only the method. You can easily change the
Example - Generic Calc
program to use this method.