Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check string for palindrome

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction.

To check whether a word is a palindrome I get the char array of the word and compare the chars. I tested it and it seems to work. However I want to know if it is right or if there is something to improve.

Here is my code:

public class Aufg1 {
    public static void main(String[] args) {
        String wort = "reliefpfpfeiller";
        char[] warray = wort.toCharArray(); 
        System.out.println(istPalindrom(warray));       
    }

    public static boolean istPalindrom(char[] wort){
        boolean palindrom = false;
        if(wort.length%2 == 0){
            for(int i = 0; i < wort.length/2-1; i++){
                if(wort[i] != wort[wort.length-i-1]){
                    return false;
                }else{
                    palindrom = true;
                }
            }
        }else{
            for(int i = 0; i < (wort.length-1)/2-1; i++){
                if(wort[i] != wort[wort.length-i-1]){
                    return false;
                }else{
                    palindrom = true;
                }
            }
        }
        return palindrom;
    }
}
like image 265
UpCat Avatar asked Nov 09 '10 21:11

UpCat


People also ask

What is palindrome string example?

A string is called a palindrome string if the reverse of that string is the same as the original string. For example, radar , level , etc. Similarly, a number that is equal to the reverse of that same number is called a palindrome number. For example, 3553, 12321, etc.

How do you reverse a string and check if its a palindrome?

The easiest way to find if a given String is Palindrome or not is by writing a recursive function to reverse the String first and then comparing the given String with the reversed String, if both are equal then the given String is a palindrome.

How do you check if a string is a palindrome in Java?

Solution approach We can use the isPalindrome() function to check if a string is a palindrome. We pass our input string as an argument and the function will return true if the string is a palindrome and false otherwise.


22 Answers

Why not just:

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

Example:

Input is "andna".
i1 will be 0 and i2 will be 4.

First loop iteration we will compare word[0] and word[4]. They're equal, so we increment i1 (it's now 1) and decrement i2 (it's now 3).
So we then compare the n's. They're equal, so we increment i1 (it's now 2) and decrement i2 (it's 2).
Now i1 and i2 are equal (they're both 2), so the condition for the while loop is no longer true so the loop terminates and we return true.

like image 134
dcp Avatar answered Oct 13 '22 15:10

dcp


You can check if a string is a palindrome by comparing it to the reverse of itself:

public static boolean isPalindrome(String str) {
    return str.equals(new StringBuilder(str).reverse().toString());
}

or for versions of Java earlier than 1.5,

public static boolean isPalindrome(String str) {
    return str.equals(new StringBuffer().append(str).reverse().toString());
}

EDIT: @FernandoPelliccioni provided a very thorough analysis of the efficiency (or lack thereof) of this solution, both in terms of time and space. If you're interested in the computational complexity of this and other possible solutions to this question, please read it!

like image 33
Greg Avatar answered Oct 13 '22 13:10

Greg


A concise version, that doesn't involve (inefficiently) initializing a bunch of objects:

boolean isPalindrome(String str) {    
    int n = str.length();
    for( int i = 0; i < n/2; i++ )
        if (str.charAt(i) != str.charAt(n-i-1)) return false;
    return true;    
}
like image 41
Andrew Mao Avatar answered Oct 13 '22 14:10

Andrew Mao


Alternatively, recursion.

For anybody who is looking for a shorter recursive solution, to check if a given string satisfies as a palindrome:

private boolean isPalindrome(String s) {
    int length = s.length();

    if (length < 2) // If the string only has 1 char or is empty
        return true;
    else {
        // Check opposite ends of the string for equality
        if (s.charAt(0) != s.charAt(length - 1))
            return false;
        // Function call for string with the two ends snipped off
        else
            return isPalindrome(s.substring(1, length - 1));
    }
}

OR even shorter, if you'd like:

private boolean isPalindrome(String s) {
    int length = s.length();
    if (length < 2) return true;
    return s.charAt(0) != s.charAt(length - 1) ? false :
            isPalindrome(s.substring(1, length - 1));
}
like image 43
Keith OYS Avatar answered Oct 13 '22 15:10

Keith OYS


Go, Java:

public boolean isPalindrome (String word) {
    String myWord = word.replaceAll("\\s+","");
    String reverse = new StringBuffer(myWord).reverse().toString();
    return reverse.equalsIgnoreCase(myWord);
}

isPalindrome("Never Odd or Even"); // True
isPalindrome("Never Odd or Even1"); // False
like image 28
Francisco Gutiérrez Avatar answered Oct 13 '22 15:10

Francisco Gutiérrez


also a different looking solution:

public static boolean isPalindrome(String s) {

        for (int i=0 , j=s.length()-1 ; i<j ; i++ , j-- ) {

            if ( s.charAt(i) != s.charAt(j) ) {
                return false;
            }
        }

        return true;
    }
like image 43
Mona Jalal Avatar answered Oct 13 '22 14:10

Mona Jalal


And here a complete Java 8 streaming solution. An IntStream provides all indexes til strings half length and then a comparision from the start and from the end is done.

public static void main(String[] args) {
    for (String testStr : Arrays.asList("testset", "none", "andna", "haah", "habh", "haaah")) {
        System.out.println("testing " + testStr + " is palindrome=" + isPalindrome(testStr));
    }
}

public static boolean isPalindrome(String str) {
    return IntStream.range(0, str.length() / 2)
            .noneMatch(i -> str.charAt(i) != str.charAt(str.length() - i - 1));
}

Output is:

testing testset is palindrome=true
testing none is palindrome=false
testing andna is palindrome=true
testing haah is palindrome=true
testing habh is palindrome=false
testing haaah is palindrome=true
like image 42
wumpz Avatar answered Oct 13 '22 15:10

wumpz


public class Palindromes {
    public static void main(String[] args) {
         String word = "reliefpfpfeiller";
         char[] warray = word.toCharArray(); 
         System.out.println(isPalindrome(warray));       
    }

    public static boolean isPalindrome(char[] word){
        if(word.length%2 == 0){
            for(int i = 0; i < word.length/2-1; i++){
                if(word[i] != word[word.length-i-1]){
                    return false;
                }
            }
        }else{
            for(int i = 0; i < (word.length-1)/2-1; i++){
                if(word[i] != word[word.length-i-1]){
                    return false;
                }
            }
        }
        return true;
    }
}
like image 27
Casey Avatar answered Oct 13 '22 15:10

Casey


public class palindrome {
public static void main(String[] args) {
    StringBuffer strBuf1 = new StringBuffer("malayalam");
    StringBuffer strBuf2 = new StringBuffer("malayalam");
    strBuf2.reverse();


    System.out.println(strBuf2);
    System.out.println((strBuf1.toString()).equals(strBuf2.toString()));
    if ((strBuf1.toString()).equals(strBuf2.toString()))
        System.out.println("palindrome");
    else
        System.out.println("not a palindrome");
}

}

like image 45
user2039532 Avatar answered Oct 13 '22 13:10

user2039532


I worked on a solution for a question that was marked as duplicate of this one. Might as well throw it here...

The question requested a single line to solve this, and I took it more as the literary palindrome - so spaces, punctuation and upper/lower case can throw off the result.

Here's the ugly solution with a small test class:

public class Palindrome {
   public static boolean isPalendrome(String arg) {
         return arg.replaceAll("[^A-Za-z]", "").equalsIgnoreCase(new StringBuilder(arg).reverse().toString().replaceAll("[^A-Za-z]", ""));
   }
   public static void main(String[] args) {
      System.out.println(isPalendrome("hiya"));
      System.out.println(isPalendrome("star buttons not tub rats"));
      System.out.println(isPalendrome("stab nail at ill Italian bats!"));
      return;
   }
}

Sorry that it is kind of nasty - but the other question specified a one-liner.

like image 42
Marc Avatar answered Oct 13 '22 13:10

Marc


Checking palindrome for first half of the string with the rest, this case assumes removal of any white spaces.

public int isPalindrome(String a) {
        //Remove all spaces and non alpha characters
        String ab = a.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
        //System.out.println(ab);

        for (int i=0; i<ab.length()/2; i++) {
            if(ab.charAt(i) != ab.charAt((ab.length()-1)-i)) {
                return 0;
            }
        }   
        return 1;
    }
like image 44
Abhilash Muthuraj Avatar answered Oct 13 '22 13:10

Abhilash Muthuraj


I'm new to java and I'm taking up your question as a challenge to improve my knowledge.

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.
like image 35
gogobebe2 Avatar answered Oct 13 '22 14:10

gogobebe2


Try this out :

import java.util.*;
    public class str {

        public static void main(String args[])
        {
          Scanner in=new Scanner(System.in);
          System.out.println("ENTER YOUR STRING: ");
          String a=in.nextLine();
          System.out.println("GIVEN STRING IS: "+a);
          StringBuffer str=new StringBuffer(a);
          StringBuffer str2=new StringBuffer(str.reverse());
          String s2=new String(str2);
          System.out.println("THE REVERSED STRING IS: "+str2);
            if(a.equals(s2))    
                System.out.println("ITS A PALINDROME");
            else
                System.out.println("ITS NOT A PALINDROME");
            }
    }
like image 34
ARAVIN Avatar answered Oct 13 '22 14:10

ARAVIN


public boolean isPalindrome(String abc){
    if(abc != null && abc.length() > 0){
        char[] arr = abc.toCharArray();
        for (int i = 0; i < arr.length/2; i++) {
            if(arr[i] != arr[arr.length - 1 - i]){
                return false;
            }
        }
        return true;
    }
    return false;
}
like image 32
Amandeep Dhanjal Avatar answered Oct 13 '22 13:10

Amandeep Dhanjal


Another way is using char Array

public class Palindrome {

public static void main(String[] args) {
    String str = "madam";
    if(isPalindrome(str)) {
        System.out.println("Palindrome");
    } else {
        System.out.println("Not a Palindrome");
    }
}

private static boolean isPalindrome(String str) {
    // Convert String to char array
    char[] charArray = str.toCharArray();  
    for(int i=0; i < str.length(); i++) {
        if(charArray[i] != charArray[(str.length()-1) - i]) {
            return false;
        }
    }
    return true;
}

}

like image 34
Madura Harshana Avatar answered Oct 13 '22 14:10

Madura Harshana


Here my analysis of the @Greg answer: componentsprogramming.com/palindromes


Sidenote: But, for me it is important to do it in a Generic way. The requirements are that the sequence is bidirectionally iterable and the elements of the sequence are comparables using equality. I don't know how to do it in Java, but, here is a C++ version, I don't know a better way to do it for bidirectional sequences.

template <BidirectionalIterator I> 
    requires( EqualityComparable< ValueType<I> > ) 
bool palindrome( I first, I last ) 
{ 
    I m = middle(first, last); 
    auto rfirst = boost::make_reverse_iterator(last); 
    return std::equal(first, m, rfirst); 
} 

Complexity: linear-time,

  • If I is RandomAccessIterator: floor(n/2) comparissons and floor(n/2)*2 iterations

  • If I is BidirectionalIterator: floor(n/2) comparissons and floor(n/2)*2 iterations plus (3/2)*n iterations to find the middle ( middle function )

  • storage: O(1)

  • No dymamic allocated memory


like image 42
Fernando Pelliccioni Avatar answered Oct 13 '22 13:10

Fernando Pelliccioni


Recently I wrote a palindrome program which doesn't use StringBuilder. A late answer but this might come in handy to some people.

public boolean isPalindrome(String value) {
    boolean isPalindrome = true;
    for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) {
        if (value.charAt(i) != value.charAt(j)) {
            isPalindrome = false;
        }
    }
    return isPalindrome;
}
like image 34
capt.swag Avatar answered Oct 13 '22 14:10

capt.swag


Using stack, it can be done like this

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str=in.nextLine();
        str.replaceAll("\\s+","");
        //System.out.println(str);
        Stack<String> stack=new Stack<String>();
        stack.push(str);
        String str_rev=stack.pop();
        if(str.equals(str_rev)){
            System.out.println("Palindrome"); 
        }else{
             System.out.println("Not Palindrome");
        }
    }
}
like image 42
aayushi Avatar answered Oct 13 '22 14:10

aayushi


 public static boolean isPalindrome(String word) {
    String str = "";
    for (int i=word.length()-1; i>=0;  i--){
        str = str + word.charAt(i);
    }
   if(str.equalsIgnoreCase(word)){
       return true;
   }else{
       return false;
   }

}
like image 38
Chandara Chea Avatar answered Oct 13 '22 15:10

Chandara Chea


Why not just :

boolean isPalindrom(String s) {
        char[] myChars = s.toCharArray();
        for (int i = 0; i < myChars.length/2; i++) {
            if (myChars[i] != myChars[myChars.length - 1 - i]) {
                return false;
            }
        }
        return true;
}
like image 35
bluesony Avatar answered Oct 13 '22 13:10

bluesony


Amazing how many different solutions to such a simple problem exist! Here's another one.

private static boolean palindrome(String s){
    String revS = "";
    String checkS = s.toLowerCase();
    String[] checkSArr = checkS.split("");

    for(String e : checkSArr){
        revS = e + revS;
    }

    return (checkS.equals(revS)) ? true : false;
}
like image 34
Felix Avatar answered Oct 13 '22 15:10

Felix


  • This implementation works for numbers and strings.
  • Since we are not writing anything, so there is no need to convert the string into the character array.
public static boolean isPalindrome(Object obj)
{
    String s = String.valueOf(obj);

    for(int left=0, right=s.length()-1; left < right; left++,right--)
    {
        if(s.charAt(left++) != s.charAt(right--))
            return false;
    }
    return true;
}
like image 31
Pratik Patil Avatar answered Oct 13 '22 15:10

Pratik Patil