Sunday, December 18, 2016

How to check if the given string is palindrome (Recursive vs Non-recursive )

Facebook

palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward, such as "level" or "kayak" or  "amanaplanacanalpanama" 

Following is the program to check if the given string is a palindrome.  



package com.mytech.today;


public class PalindromeClient {


    public static boolean isPalendrome (String s) {

        if(s== null) {
            throw new RuntimeException("null value passed");
        }

        int n = s.length();
        if(n==1) return true;
        else {

            for (int i=0; i < n/2 ; i++) {
                if(s.charAt(i)!=s.charAt(n-i-1)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean isPalendromeRecurrsive (String s) {

        if (s.length()<2) { return true;}
        else if (s.charAt(0)==s.charAt(s.length()-1)) {
            return isPalendrome(s.substring(1, s.length()-1));
        }
        else return false;

    }

    public static void main(String[] args) {
        System.out.println(isPalendrome("levvel"));
        System.out.println(isPalendrome("manaplanacanalpanama"));
        System.out.println(isPalendrome("a"));
        System.out.println(isPalendrome("jptt aefa afdaf"));

        System.out.println(isPalendromeRecurrsive("levvel"));
        System.out.println(isPalendromeRecurrsive("manaplanacanalpanama"));
        System.out.println(isPalendromeRecurrsive("a"));
        System.out.println(isPalendromeRecurrsive("jptt aefa afdaf"));
    }
}

0 comments:

Post a Comment

I love to entertain onymous user Comment !

Pages

 ©mytechtoday.com 2006-2010

 ©Mytechtoday

TOP