SHARE
TWEET

palindrome

DulcetAirman Apr 19th, 2018 (edited) 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
  12.     // one symbol in two chars (surrogate pair):
  13.     final String clef = "\uD834\uDD1E";
  14.     test(clef + clef, true);
  15.   }
  16.  
  17.   static void test(final String a, final boolean expected) {
  18.     final boolean actual = testPalindrome(a);
  19.     (actual == expected ? System.out : System.err).format("'%s' => %s%n", a, actual);
  20.   }
  21.  
  22.   /**
  23.    * is the given string a palindrome?
  24.    *
  25.    * Note: this doesn't work with surrogate pairs.
  26.    *
  27.    * @param str
  28.    *          the string to be tested
  29.    * @return true if it's a palindrome.
  30.    */
  31.   public static boolean testPalindrome(final String str) {
  32.     final int last = str.length() - 1;// last valid index
  33.     if (-1 == last) // empty string is a palindrome
  34.       return true;
  35.     final int m = last / 2; // last index to be checked. first is 0.
  36.     for (int i = 0; i <= m; i++)
  37.       if (str.charAt(i) != str.charAt(last - i))
  38.         return false;
  39.     return true;
  40.   }
  41.  
  42. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top