Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java way to check if a string is palindrome [duplicate]

Tags:

java

string

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

like image 453
Mithun Sasidharan Avatar asked Dec 09 '11 11:12

Mithun Sasidharan


3 Answers

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;
}
like image 120
Jeff Foster Avatar answered Sep 28 '22 04:09

Jeff Foster


For the least lines of code and the simplest case

if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
like image 32
Peter Lawrey Avatar answered Sep 28 '22 05:09

Peter Lawrey


Here is a simple one"

public class Palindrome {

    public static void main(String [] args){
        Palindrome pn = new Palindrome();

        if(pn.isPalindrome("ABBA")){
            System.out.println("Palindrome");
        } else {
            System.out.println("Not Palindrome");
        }   
    }

    public boolean isPalindrome(String original){
        int i = original.length()-1;
        int j=0;
        while(i > j) {
            if(original.charAt(i) != original.charAt(j)) {
                return false;
            }
            i--;
            j++;
        }
        return true;
    }
}
like image 33
kaila88 Avatar answered Sep 28 '22 03:09

kaila88