Creating a recursive method for Palindrome

前端 未结 21 1992
野的像风
野的像风 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 06:54

    Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:

    private static boolean isPalindrome(String str, int left, int right) {
        if(left >= right) {
            return true;
        }
        else {
            if(str.charAt(left) == str.charAt(right)) {
    
                return isPalindrome(str, ++left, --right);
            }
            else {
                return false;
            }
        }
    }
    
    
     public static void main(String []args){
        String str = "abcdcbb"; 
        System.out.println(isPalindrome(str, 0, str.length()-1));
     }
    

提交回复
热议问题