Code Pretty Print Script

Thursday, December 12, 2013

Palindromes

How can you efficiently tell if a word is a palindrome? You could always reverse your input, and then test that reversed String against your initial input String (because they'll be equal if the input is a palindrome, by definition). Or, you could use my Stack and do this.
/**
 * Determine if the input is a palindrome.
 */
public static boolean isPalindrome(char[] in) {
  if (in == null) { // null isn't.
    return false;
  }
  int len = in.length;
  if (len < 2) { // one (or zero), is.
    return true;
  }
  boolean isOdd = (len & 1) != 0;
  int halfLen = len >> 1;
  Stack<Character> charStack = new Stack<Character>();
  for (int i = 0; i < halfLen; i++) {
    charStack.push(in[i]);
  }
  if (isOdd) {
    halfLen++;
  }
  for (int i = halfLen; i < len; i++) {
    if (in[i] != charStack.pop()) {
      return false;
    }
  }
  return true;
}

No comments :

Post a Comment