Advertisement
DulcetAirman

palindrome recursive

Apr 19th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. package ch.fhnw.claudemartin;
  2.  
  3. public class SomeClass {
  4.   public static void main(final String[] args) {
  5.     test("", true);
  6.     test("12345", false);
  7.     test("racecar", true);
  8.     test("Madam", false);
  9.     test("abcdefgfedcba", true);
  10.     test("abcdefggfedcba", true);
  11.     test("abcdefggxfedcba", false);
  12.  
  13.     // one symbol in two chars (surrogate pair):
  14.     final String clef = "\uD834\uDD1E";
  15.     test(clef + clef, true);
  16.   }
  17.  
  18.   static void test(final String a, final boolean expected) {
  19.     final boolean actual = testPalindrome(a);
  20.     (actual == expected ? System.out : System.err).format("'%s' => %s%n", a, actual);
  21.   }
  22.  
  23.   /**
  24.    * is the given string a palindrome?
  25.    *
  26.    * Note: this doesn't work with surrogate pairs.
  27.    *
  28.    * @param str
  29.    *          the string to be tested
  30.    * @return true if it's a palindrome.
  31.    */
  32.   public static boolean testPalindrome(final String str) {
  33.     final int last = str.length() - 1;
  34.     if (-1 == last)
  35.       return true;
  36.     return testPalindrome(str, 0, last);
  37.   }
  38.  
  39.   private static boolean testPalindrome(final String str, final int offset, final int last) {
  40.     if (str.charAt(offset) != str.charAt(last - offset))
  41.       return false;
  42.     if (offset == last / 2)
  43.       return true;
  44.     return testPalindrome(str, 1 + offset, last);
  45.   }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement