Wednesday, 17 June 2015

Check whether a given String/Number is a palindrome - Java program

This post is about finding that a given string/number is a palindrome or not. Remember a string or a number is a palindrome if it remains unchanged when reversed, for example "madam" is a palindrome as reverse of the madam is again madam. Another example is "malayalam" or 12344321.

Here three ways are given to do that for String and one for integer. First 2 ways use the inbuilt String functions to do that.

In the first method checkPalindrome1(), StringBuilder class instance is used which is instantiated using the given string, then the inbuilt reverse method of the StringBuilder is used. If the given string is a palindrome then reverse of the string should be same as the original string.

Second method checkPalindrome2() is same as the first method, it works on the logic that the second half of the string is the mirror image of the first half so if econd half of the string is reversed then it should be same as the first half.
As exp if we have a string 12344321 then the sercond half 4321 when reversed will become 1234 which is equal to the first half, thus string is a palindrome.
In this logic whether a given string is of even length or odd length matters. That's why the ternary operator while creating the StringBuilder object.

index + index == str.length() ? str.substring(index) : str.substring(index + 1)

Third method checkPalindrome3() doesn't use any inbuilt function. In this method we start from the end of the string and read one character at a time to create a new String. Now if a given string is a palindrome then the new string should be equal to the original string.

Fourth method checkPalindrome4() is for number, though we can convert number to string and use any of the above mentioned methods but in a scenario where we have to do it for number this logic can be used.

public class Palindrome {
    public static void main(String[] args) {
        Palindrome pm = new Palindrome();
        pm.checkPalindrome1("DogeeseseeGod");
        pm.checkPalindrome2("malayalam");
        pm.checkPalindrome3("1234442");
        pm.checkPalindrome4(12344321);
    }
    
    private void checkPalindrome1(String str){            
        StringBuilder sb = new StringBuilder(str);
        // reverse the string and check if it is equal to original 
        // string
        if(str.equalsIgnoreCase(sb.reverse().toString())){
            System.out.println(str + " is a Palindrome");
        }else{
            System.out.println(str + " is not a Palindrome");
        }        
    }
    
    /**
     * In a palindrome one half of the string is the mirror image of the other
     * this logic is based on that
     * @param str
     */
    private void checkPalindrome2(String str){        
        int index = str.length()/2;        
        StringBuilder sb = new StringBuilder(index + index == str.length() 
                ? str.substring(index) : str.substring(index + 1));
        if(str.substring(0, index).equalsIgnoreCase(sb.reverse().toString())){
            System.out.println(str + " is a Palindrome");
        }else{
            System.out.println(str + " is not a Palindrome");
        }        
    }        
    
    /**
     * If no inbuilt function has to be used.
     * 
     * @param str
     */
    private void checkPalindrome3(String str){
        StringBuilder sb = new StringBuilder();
        // start reading the string backward
        for(int i = str.length() - 1; i >= 0; i--){
            sb.append(str.charAt(i));
        }            
        System.out.println("string 3 " + sb.toString());
        if(str.equalsIgnoreCase(sb.toString())){
            System.out.println(str + " is a Palindrome");
        }else{
            System.out.println(str + " is not a Palindrome");
        }
        
    }

    /**
    * To check for integers
    * @param num
    */
    private void checkPalindrome4(int num){
        int reverse = 0;
        int remainder;
        int originalNum = num;
        while (num > 0) {
            remainder = num % 10;
            reverse = (reverse * 10) + remainder;
            num = num / 10;
        }
        if(reverse == originalNum){
            System.out.println(originalNum + " is a Palindrome");
        }else{
            System.out.println(originalNum + " is not a Palindrome");
        }
    }

}

So these are the ways to find if a given string is a palindrome or not. Please let me know if you have any other logic to do that.


Related Topics

  1. How to find the longest palindrome in the given String
  2. Check if given strings are anagram or not
  3. Print odd-even numbers using threads and wait-notify
  4. Count number of words in a String
  5. How to add double quotes to a String

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment