Java Reference
In-Depth Information
// Both are letters.
if (first == last)
{
// Remove both first and last character.
Sentence shorter = new
Sentence(text.substring(1, length - 1));
return shorter.isPalindrome();
}
else
return false;
}
else if (!Character.isLetter(last))
{
// Remove last character.
Sentence shorter = new
Sentence(text.substring(0, length - 1));
return shorter.isPalindrome();
}
else
{
// Remove first character.
Sentence shorter = new
Sentence(text.substring(1));
return shorter.isPalindrome();
}
}
13.3 Recursive Helper Methods
Sometimes it is easier to find a recursive solution if you change the original problem
slightly. Then the original problem can be solved by calling a recursive helper method.
Sometimes it is easier to find a recursive solution if you make a slight change to
the original problem.
Here is a typical example. Consider the palindrome test of How To 13.1. It is a bit
inefficient to construct new Sentence objects in every step. Now consider the
following change in the problem. Rather than testing whether the entire sentence is a
palindrome, let's check whether a substring is a palindrome:
600
601
/**
Search WWH ::




Custom Search