public class Palindrome1 {
public static void main(String[] args) {
String str = "racecar";
boolean isPalindrome = isPalindromeRecursive(str);
System.out.println("递归算法,字符串 '" + str + "' 是否是回文: " + isPalindrome);
}
public static boolean isPalindromeRecursive(String str) {
if (str.length() <= 1) {
return true;
}
char first = str.charAt(0);
char last = str.charAt(str.length() - 1);
if (first != last) {
return false;
}
String subStr = str.substring(1, str.length() - 1);
return isPalindromeRecursive(subStr);
}
}
// public class Palindrome2 {
// public static void main(String[] args) {
// String str = "racecar";
// boolean isPalindrome = isPalindromeIterative(str);
// System.out.println("递推算法,字符串 '" + str + "' 是否是回文: " + isPalindrome);
// }
// public static boolean isPalindromeIterative(String str) {
// int left = 0;
// int right = str.length() - 1;
// while (left < right) {
// if (str.charAt(left) != str.charAt(right)) {
// return false;
// }
// left++;
// right--;
// }
// return true;
// }
// }