1 public class Palindromes
2 {
3 public static void main(String[] args)
4 {
5 String sentence1 = "Madam, I'm Adam!";
6 System.out.println(sentence1);
7 System.out.println("Palindrome: " + isPalindrome(sentence1));
8 String sentence2 = "Sir, I'm Eve!";
9 System.out.println(sentence2);
10 System.out.println("Palindrome: " + isPalindrome(sentence2));
11 }
12
13 /**
14 Tests whether a text is a palindrome.
15 @param text a string that is being checked
16 @return true if text is a palindrome, false otherwise
17 */
18 public static boolean isPalindrome(String text)
19 {
20 return isPalindrome(text, 0, text.length() - 1);
21 }
22
23 /**
24 Tests whether a substring is a palindrome.
25 @param text a string that is being checked
26 @param start the index of the first character of the substring
27 @param end the index of the last character of the substring
28 @return true if the substring is a palindrome
29 */
30 public static boolean isPalindrome(String text, int start, int end)
31 {
32 // Separate case for substrings of length 0 and 1.
33 if (start >= end) { return true; }
34 else
35 {
36 // Get first and last characters, converted to lowercase.
37 char first = Character.toLowerCase(text.charAt(start));
38 char last = Character.toLowerCase(text.charAt(end));
39 if (Character.isLetter(first) && Character.isLetter(last))
40 {
41 if (first == last)
42 {
43 // Test substring that doesn’t contain the matching letters.
44 return isPalindrome(text, start + 1, end - 1);
45 }
46 else
47 {
48 return false;
49 }
50 }
51 else if (!Character.isLetter(last))
52 {
53 // Test substring that doesn’t contain the last character.
54 return isPalindrome(text, start, end - 1);
55 }
56 else
57 {
58 // Test substring that doesn’t contain the first character.
59 return isPalindrome(text, start + 1, end);
60 }
61 }
62 }
63 }