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
9: (
10: "\nThis program tests some strings and "
11: + "reports whether they are palindromes.\n"
12: );
13: System.out.println
14: (
15: "\"noon\""
16: + (isPalindrome("noon", 0, "noon".length() - 1)
17: ? " is " : " is not ") + "a palindrome."
18: );
19: System.out.println
20: (
21: "\"eve\""
22: + (isPalindrome("eve", 0, "eve".length() - 1)
23: ? " is " : " is not ") + "a palindrome."
24: );
25: System.out.println
26: (
27: "\"morn\""
28: + (isPalindrome("morn", 0, "morn".length() - 1)
29: ? " is " : " is not ") + "a palindrome."
30: );
31: String testStr = "ablewasiereisawelba";
32: System.out.println
33: (
34: testStr
35: + (isPalindrome(testStr, 0, testStr.length() - 1)
36: ? " is " : " is not ") + "a palindrome."
37: );
38: testStr = "amanaplanacanalpanama";
39: System.out.println
40: (
41: testStr
42: + (isPalindrome(testStr, 0, testStr.length() - 1)
43: ? " is " : " is not ") + "a palindrome."
44: );
45: testStr = "amanaplanacanapanama";
46: System.out.println
47: (
48: testStr
49: + (isPalindrome(testStr, 0, testStr.length() - 1)
50: ? " is " : " is not ") + "a palindrome."
51: );
52: }
54: public static boolean isPalindrome
55: (
56: String s,
57: int first,
58: int last
59: )
60: /** Determine whether a string is a palindrome.
61: @return true if s is a palindrome between the indices first
62: and last (inclusive), false otherwise.
63: @param s The full string to be tested.
64: @param first The lower index of the portion of the string
65: to be tested on the current call.
66: @param The upper index of the portion of the string to be
67: tested on the current call.
68: <p>Pre:<p>s contains a non-empty string object and
69: 0 <= first, last <= s.length().
70: Post:<p>No side effects.
71: */
72: {
73: if (first >= last)
74: return true;
75: else
76: return (s.charAt(first) == s.charAt(last) &&
77: isPalindrome(s, first + 1, last - 1));
78: }
79: }