Java Reference
In-Depth Information
ȗ
The empty string
We don't have to come up with a special solution for strings with two characters.
Step 2 still applies to those stringsȌeither or both of the characters are removed.
But we do need to worry about strings of length 0 and 1. In those cases, Step 2
can't apply. There aren't two characters to remove.
The empty string is a palindromeȌit's the same string when you read it
backwards. If you find that too artificial, consider a string "mm" . According to the
rule discovered in Step 2, this string is a palindrome if the first and last characters
of that string match and the remainderȌthat is, the empty stringȌis also a
palindrome. Therefore, it makes sense to consider the empty string a palindrome.
A string with a single letter, such as "I" , is a palindrome. How about the case in
which the character is not a letter, such as "!" ? Removing the ! yields the empty
string, which is a palindrome. Thus, we conclude that all strings of length 0 or 1
are palindromes.
Step 4 Implement the solution by combining the simple cases and the reduction
step.
Now you are ready to implement the solution. Make separate cases for the simple
inputs that you considered in Step 3. If the input isn't one of the simplest cases,
then implement the logic you discovered in Step 2.
Here is the isPalindrome method.
public boolean isPalindrome()
{
int length = text.length();
// Separate case for shortest strings.
if (length <= 1) return true;
// Get first and last characters, converted to lowercase.
char first =
Character.toLowerCase(text.charAt(0));
char last =
Character.toLowerCase(text.charAt(length - 1));
if (Character.isLetter(first) &&
Character.isLetter(last))
{
599
600
Search WWH ::




Custom Search