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

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 related to java string

The answer is


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;
    }
}

I guess this is simple way to check palindrome

String strToRevrse = "MOM";

strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString());

 public boolean isPalindrom(String text) {
    StringBuffer stringBuffer = new StringBuffer(text);
     return stringBuffer.reverse().toString().equals(text);
}

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;
}

For the least lines of code and the simplest case

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

Here's a good class :

public class Palindrome {

  public static boolean isPalindrome(String stringToTest) {
    String workingCopy = removeJunk(stringToTest);
    String reversedCopy = reverse(workingCopy);

    return reversedCopy.equalsIgnoreCase(workingCopy);
  }

  protected static String removeJunk(String string) {
    int i, len = string.length();
    StringBuffer dest = new StringBuffer(len);
    char c;

    for (i = (len - 1); i >= 0; i--) {
      c = string.charAt(i);
      if (Character.isLetterOrDigit(c)) {
        dest.append(c);
      }
    }

    return dest.toString();
  }

  protected static String reverse(String string) {
    StringBuffer sb = new StringBuffer(string);

    return sb.reverse().toString();
  }

  public static void main(String[] args) {
    String string = "Madam, I'm Adam.";

    System.out.println();
    System.out.println("Testing whether the following "
        + "string is a palindrome:");
    System.out.println("    " + string);
    System.out.println();

    if (isPalindrome(string)) {
      System.out.println("It IS a palindrome!");
    } else {
      System.out.println("It is NOT a palindrome!");
    }
    System.out.println();
  }
}

Enjoy.


public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
    if (word[i1] != word[i2]) {
        return false;
    }
    ++i1;
    --i2;
}
return true;
}

import java.util.Scanner;

public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;

public void allSubstrings(String s){        
    for(int i=0;i<s.length();i++){
        for(int j=1;j<=s.length()-i;j++){
            String subString=s.substring(i, i+j);  
            palindrome(subString);             
        }
    }
        }   
public void palindrome(String sub){
    System.out.println("String to b checked is "+sub);
    StringBuilder sb=new StringBuilder();
    sb.append(sub);     // append string to string builder 
    sb.reverse();        
    if(sub.equals(sb.toString())){                        // palindrome condition 
        System.out.println("the given String :"+sub+" is a palindrome");
        longestPalindrome(sub);
    }
    else{
        System.out.println("the string "+sub+"iss not a palindrome");
    }
        }
public void longestPalindrome(String s){
            if(s.length()>longest){                 
        longest=s.length();
        longestPalindrome=s;

    }
    else if (s.length()==longest){    
        oldPalindrome=longestPalindrome;
        longestPalindrome=s;

    }




}

public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();

    Scanner sc=new Scanner(System.in);    
    System.out.println("Enter the String ::");
    String s=sc.nextLine(); 
    fp.allSubstrings(s);      
    sc.close();
    if(fp.oldPalindrome.length()>0){
    System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");  
    }
    else{
        System.out.println(longestPalindrome+":is the longest palindrome`````");
    }}
}

I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:

import java.util.ArrayList;
import java.util.List;

public class PalindromeRecursiveBoolean {

    public static boolean isPalindrome(String str) {

        str = str.toUpperCase();
        char[] strChars = str.toCharArray();

        List<Character> word = new ArrayList<>();
        for (char c : strChars) {
            word.add(c);
        }

        while (true) {
            if ((word.size() == 1) || (word.size() == 0)) {
                return true;
            }
            if (word.get(0) == word.get(word.size() - 1)) {
                word.remove(0);
                word.remove(word.size() - 1);
            } else {
                return false;

            }

        }
    }
}
  1. If the string is made of no letters or just one letter, it is a palindrome.
  2. Otherwise, compare the first and last letters of the string.
    • If the first and last letters differ, then the string is not a palindrome
    • Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.

The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'


check this condition

String string="//some string...//"

check this... if(string.equals((string.reverse()) { it is palindrome }