Java Reference
In-Depth Information
Tests whether a substring of the sentence is a palindrome.
@param start
the index of the first character of the substring
@param end
the index of the last character of the substring
@return true
if the substring is a palindrome
*/
public boolean isPalindrome(int start, int end)
This method turns out to be even easier to implement than the original test. In the
recursive calls, simply adjust the
start
and
end
parameters to skip over matching
letter pairs and characters that are not letters. There is no need to construct new
Sentence
objects to represent the shorter strings.
public boolean isPalindrome(int start, int end)
{
// Separate case for substrings of length 0 and 1.
if (start >= end) return true;
// Get first and last characters, converted to lowercase.
char first =
Character.toLowerCase(text.charAt(start));
char last =
Character.toLowerCase(text.charAt(end));
if (Character.isLetter(first) &&
Character.isLetter(last))
{
if (first == last)
{
// Test substring that doesn't contain the matching letters.
return isPalindrome(start + 1, end - 1);
}
else
return false;
}
else if (!Character.isLetter(last))
{
// Test substring that doesn't contain the last character.
return isPalindrome(start, end - 1);
}
else
{
// Test substring that doesn't contain the first character.
return isPalindrome(start + 1, end);
}