Creating a recursive method for Palindrome

前端 未结 21 1931
野的像风
野的像风 2020-12-03 06:28

I am trying to create a Palindrome program using recursion within Java but I am stuck, this is what I have so far:

 public static void main (String[] args){
         


        
21条回答
  •  無奈伤痛
    2020-12-03 07:00

    Here are three simple implementations, first the oneliner:

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

    This is ofcourse quite slow since it creates a stringbuffer and reverses it, and the whole string is always checked nomatter if it is a palindrome or not, so here is an implementation that only checks the required amount of chars and does it in place, so no extra stringBuffers:

    public static boolean isPalindrome(String str){
    
        if(str.isEmpty()) return true;
    
        int last = str.length() - 1;        
    
        for(int i = 0; i <= last / 2;i++)
            if(str.charAt(i) != str.charAt(last - i))
                return false;
    
        return true;
    }
    

    And recursively:

    public static boolean recursivePalin(String str){
        return check(str, 0, str.length() - 1);
    }
    
    private static boolean check (String str,int start,int stop){
        return stop - start < 2 ||
               str.charAt(start) == str.charAt(stop) &&
               check(str, start + 1, stop - 1);
    }
    

提交回复
热议问题