Ask Questions?

View Latest Questions

Advertisement


 
 

Exercise - Palindrome
Posted on: July 26, 2006 at 12:00 AM
Write a method which returns true if the string parameter is a palindrome.

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

CallReturnsComments
isPalindrome("Hello")falseNot a palindrome.
isPalindrome("radar")trueIs a palindrome.
isPalindrome("Able was I ere I saw elba.")trueIs 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.
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-11-23
Advertisement


DMCA.com