Creating a recursive method for Palindrome

前端 未结 21 1993
野的像风
野的像风 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:07

    Here is a recursive method that will ignore specified characters:

    public static boolean isPal(String rest, String ignore) {
        int rLen = rest.length();
        if (rLen < 2)
            return true;
        char first = rest.charAt(0)
        char last = rest.charAt(rLen-1);
        boolean skip = ignore.indexOf(first) != -1 || ignore.indexOf(last) != -1;
        return skip || first == last && isPal(rest.substring(1, rLen-1), ignore);
    }
    

    Use it like this:

    isPal("Madam I'm Adam".toLowerCase(), " ,'");
    isPal("A man, a plan, a canal, Panama".toLowerCase(), " ,'");
    

    It does not make sense to include case insensitivity in the recursive method since it only needs to be done once, unless you are not allowed to use the .toLowerCase() method.

提交回复
热议问题