Java way to check if a string is palindrome

18

I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations

This question is tagged with java string

~ Asked on 2011-12-09 11:19:58

The Best Answer is


118

Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.

The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.

boolean isPalindrome(String s) {
  int n = s.length();
  for (int i = 0; i < (n/2); ++i) {
     if (s.charAt(i) != s.charAt(n - i - 1)) {
         return false;
     }
  }

  return true;
}

~ Answered on 2011-12-09 11:27:05


25

For the least lines of code and the simplest case

if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.

~ Answered on 2011-12-09 11:34:05


Most Viewed Questions: