public class TestPalindrome
1: //TestPalindrome.java
2: //Determines if a string is a palindrome.
4: public class TestPalindrome
5: {
6: public static void main(String[] args)
7: {
8: System.out.println("\nThis program tests some strings and "
9: + "reports whether they are palindromes.\n");
10: System.out.println("\"noon\""
11: + (isPalindrome("noon", 0, "noon".length() - 1)
12: ? " is " : " is not ") + "a palindrome.");
13: System.out.println("\"eve\""
14: + (isPalindrome("eve", 0, "eve".length() - 1)
15: ? " is " : " is not ") + "a palindrome.");
16: System.out.println("\"morn\""
17: + (isPalindrome("morn", 0, "morn".length() - 1)
18: ? " is " : " is not ") + "a palindrome.");
19: System.out.println("\"ablewasiereisawelba\""
20: + (isPalindrome("ablewasiereisawelba", 0,
21: "ablewasiereisawelba".length() - 1)
22: ? " is " : " is not ") + "a palindrome.");
23: System.out.println("\"amanaplanacanalpanama\""
24: + (isPalindrome("amanaplanacanalpanama", 0,
25: "amanaplanacanalpanama".length() - 1)
26: ? " is " : " is not ") + "a palindrome.");
27: System.out.println("\"amanaplanacanapanama\""
28: + (isPalindrome("amanaplanacanapanama", 0,
29: "amanaplanacanapanama".length() - 1)
30: ? " is " : " is not ") + "a palindrome.");
31: }
33: public static boolean isPalindrome
34: (
35: String s,
36: int first,
37: int last
38: )
39: /**<
40: Determine whether a string is a palindrome.
41: @return true if s is a palindrome between the indices first
42: and last (inclusive), false otherwise.
43: @param s The full string to be tested.
44: @param first The lower index of the portion of the string
45: to be tested on the current call.
46: @param The upper index of the portion of the string to be
47: tested on the current call.
48: <p>Pre:<p>s contains a non-empty string object and
49: 0 <= first, last <= s.length().
50: Post:<p>No side effects.
51: */
52: {
53: if (first >= last)
54: return true;
55: else
56: return (s.charAt(first) == s.charAt(last) &&
57: isPalindrome(s, first+1, last-1));
58: }
59: }