Вспомните о палиндроме:
risetovotesir
Это можно построить, начав с палиндрома v
(односимвольная строка - это всегда палиндром, как и пустая строка) и добавив одну и ту же букву вперед и назад:
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'.
Процесс, используемый этой рекурсивной функцией, идет в обратном направлении, разбивая строку по частям. Он определяет, действительно ли это палиндром, если оба:
- первый и последний символы равны; и
- внутренняя часть строки (после удаления этих двух) - палиндром.
Следовательно, код можно записать как:
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's NOT palindromic.
if (str.charAt (0) != str.charAt (str.length() - 1))
return false;
// Otherwise it's palindromic only if the inner string is palindromic.
return isPalindrome (str.substring (1, str.length () - 1));
}
Используя строку peed deep
, различные уровни:
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.
В качестве альтернативы, непалиндром (хотя и мучительно близко), равный star rots
, дает вам:
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.