Creating a recursive method for Palindrome

前端 未结 21 1989
野的像风
野的像风 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 06:45

    there's no code smaller than this:

    public static boolean palindrome(String x){
        return (x.charAt(0) == x.charAt(x.length()-1)) && 
            (x.length()<4 || palindrome(x.substring(1, x.length()-1)));
    }
    

    if you want to check something:

    public static boolean palindrome(String x){
        if(x==null || x.length()==0){
            throw new IllegalArgumentException("Not a valid string.");
        }
        return (x.charAt(0) == x.charAt(x.length()-1)) && 
            (x.length()<4 || palindrome(x.substring(1, x.length()-1)));
    }
    

    LOL B-]

提交回复
热议问题