Think of a palindrome:
risetovotesir
This can be created starting with the palindrome v (a single-character string is always a palindrome, like an empty string) and adds the same letter to the beginning and back:
v Start with palindrome 'v'. ovo Add 'o' to both ends. tovot Then 't'. etovote Then 'e'. setovotes Then 's'. isetovotesi Then 'i'. risetovotesir And finally 'r'.
The process used by this recursive function is in the opposite direction, breaking the bit in half. It determines if this is a palindrome, if both:
- the first and last characters are equal; and
- the inside of the line (after removing these two) is the palindrome.
Therefore, the code can be written as:
public static boolean isPalindrome (String str) { // Zero- or one-character string is a palindrome. if (str.length() < 2) return true; // If first and last characters are different, it NOT palindromic. if (str.charAt (0) != str.charAt (str.length() - 1)) return false; // Otherwise it palindromic only if the inner string is palindromic. return isPalindrome (str.substring (1, str.length () - 1)); }
Using the peed deep line, different levels:
1. length 9 >= 2, both ends are 'p', next level checks 'eed dee'. 2. length 7 >= 2, both ends are 'e', next level checks 'ed de'. 3. length 5 >= 2, both ends are 'e', next level checks 'd d'. 4. length 3 >= 2, both ends are 'd', next level checks ' ' (space). 5. length 1 < 2, return true.
Alternatively, the non-palindrome (albeit painfully close) star rots gives you:
1. length 9 >= 2, both ends are 's', next level checks 'tar rot'. 2. length 7 >= 2, both ends are 't', next level checks 'ar ro'. 3. length 5 >= 2, ends are 'a' and 'o', so return false.