20

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

Mithun Sasidharan
  • 20,572
  • 10
  • 34
  • 52
  • 1
    http://stackoverflow.com/questions/248161/palindrome-detection-efficiency – Andy Dec 09 '11 at 11:22
  • 1
    @Andy : That is to detect the efficiency of the same. I want the code in the simplest way with least number of line of codes and methods used!! – Mithun Sasidharan Dec 09 '11 at 11:26

11 Answers11

121

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;
}
Raphaël
  • 3,646
  • 27
  • 28
Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
  • 6
    Probably the fastest solution executionwise. – RokL Dec 09 '11 at 11:48
  • Can this solution be altered to take a character as input rather than a string? I am searching for the same palindrome solution but with character input. Also can I ask if the For loop is indeed checking each character from either half of the string and comparing them? Thanks –  Dec 10 '13 at 23:01
  • 4
    A single character is always a palindrome. – Joel Christophel Nov 12 '14 at 03:45
  • 1
    you don't need to compare the centre character when the length is odd. So you can simply have : `for (int i=0;i<(n / 2);++i)` – Haider Apr 29 '16 at 02:44
  • This is close, but wouldn't whitespace or punctuation mess it up? Should you clean the string first? – Randy Oct 05 '16 at 20:45
  • Its fast... but most people ask this question to learn about string and char manipulation.. Doing it like this without reversing the string.. you arnt learning much but logic. – NightSkyCode Oct 24 '16 at 00:41
  • ` public boolean isPalindrone (String checkPalindrome) { int length = checkPalindrome.length(); int mid = length/2; int i,j=0; for (i=0, j=length-1; i < mid ; i++, j--) { if (checkPalindrome.charAt(i) != checkPalindrome.charAt(j)) break; } if (i == mid) return true; else return false; }` – user358591 Nov 19 '16 at 04:45
  • As the complexity of String.length() function is O(1) you can even avoid creating a new variable for saving length ` public boolean isPalindrom(String str){` for(int i =0; i – Andrew Vakhniuk Apr 12 '19 at 15:21
  • @AndrewVakhniuk wrong. The time complexity is O(n), where n is the number of characters in the string. The space complexity is O(1). – Lesair Valmont Sep 02 '20 at 00:04
  • @LesairValmont , Why am i wrong, can you prove? I took this answer from here and there is written that length is stored - https://stackoverflow.com/questions/20264227/what-is-complexity-of-length-function-in-string-class-of-java – Andrew Vakhniuk Sep 04 '20 at 07:40
  • @AndrewVakhniuk yes, fetching the value of str.length is a O(1) time complexity operation, because the JDK caches it and doesn't recalculate it every time you read it, however, all the processing you do inside of the for loop, makes it an O(n) operation. Ask yourself this question: is this algorithm going to have the same runtime if str.length() equals to 3 than if it is equal to Integer.MAX_VALUE? – Lesair Valmont Sep 05 '20 at 12:30
  • @LesairValmont Why do you say, that all the processing inside the loop makes it O(n)?? The array is never changed , so the cache value is always the same, is not it so? – Andrew Vakhniuk Sep 06 '20 at 13:13
25

For the least lines of code and the simplest case

if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    Very nice, but removal of spaces might be a better deal: return str.replaceAll("\\s", "").equals(new StringBuilder(str.replaceAll("\\s", "")).reverse().toString())+""; ` – Beezer Apr 03 '19 at 09:54
12

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;
    }
}
leocborges
  • 4,799
  • 5
  • 32
  • 38
kaila88
  • 127
  • 1
  • 6
8

You can try something like this :

    String variable = ""; #write a string name

    StringBuffer rev = new StringBuffer(variable).reverse(); 

    String strRev = rev.toString(); 

    if(variable.equalsIgnoreCase(strRev)) # Check the condition
Mithun Sasidharan
  • 20,572
  • 10
  • 34
  • 52
7

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.

amrfaissal
  • 1,060
  • 1
  • 7
  • 18
  • public boolean isPalindrone (String checkPalindrome) { int length = checkPalindrome.length(); int mid = length/2; int i,j=0; for (i=0, j=length-1; i < mid ; i++, j--) { if (checkPalindrome.charAt(i) != checkPalindrome.charAt(j)) break; } if (i == mid) return true; else return false; } – user358591 Nov 19 '16 at 04:44
3
 public boolean isPalindrom(String text) {
    StringBuffer stringBuffer = new StringBuffer(text);
     return stringBuffer.reverse().toString().equals(text);
}
2

I guess this is simple way to check palindrome

String strToRevrse = "MOM";

strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString());
Prakash_se7en
  • 88
  • 2
  • 3
  • 16
1

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'

gogobebe2
  • 324
  • 2
  • 4
  • 18
0
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;
}
Syed Raza Mehdi
  • 4,067
  • 1
  • 31
  • 47
0
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`````");
    }}
}
imsolo
  • 39
  • 4
0

check this condition

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

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

Shemil
  • 387
  • 1
  • 7
  • 12