1 public class Sentence
2 {
3 private String text;
4
5 /**
6 Constructs a sentence.
7 @param aText a string containing all characters of the sentence
8 */
9 public Sentence(String aText)
10 {
11 text = aText;
12 }
13
14 /**
15 Tests whether this sentence is a palindrome.
16 @return true if this sentence is a palindrome, false otherwise
17 */
18 public boolean isPalindrome()
19 {
20 int length = text.length();
21
22 // Separate case for shortest strings.
23 if (length <= 1) return true;
24
25 // Get first and last characters, converted to lowercase.
26 char first = Character.toLowerCase(text.charAt(0));
27 char last = Character.toLowerCase(text.charAt(length - 1));
28
29 if (Character.isLetter(first) && Character.isLetter(last))
30 {
31 // Both are letters.
32 if (first == last)
33 {
34 // Remove both first and last character.
35 Sentence shorter = new Sentence(text.substring(1, length - 1));
36 return shorter.isPalindrome();
37 }
38 else
39 {
40 return false;
41 }
42 }
43 else if (!Character.isLetter(last))
44 {
45 // Remove last character.
46 Sentence shorter = new Sentence(text.substring(0, length - 1));
47 return shorter.isPalindrome();
48 }
49 else
50 {
51 // Remove first character.
52 Sentence shorter = new Sentence(text.substring(1));
53 return shorter.isPalindrome();
54 }
55 }
56 }