递归回文函数不断返回默认结果值?

Recursive palindrome function keeps returning default result value?

public static String check(String str)
{
    String result = "";

    // Strips the string down to only letters a-z and numbers 0-9, and makes it lowercase
    str = str.replaceAll("[^A-Za-z0-9]", "");
    str = str.replaceAll("\s+","");
    str = str.toLowerCase();

    if (str.length() < 1) 
    {
        result = "The string is a palindrome";
    }
    else if ((str.charAt(str.length() - 1)) == (str.charAt(0)))
    {
        StringBuilder sb = new StringBuilder(str);
        sb.deleteCharAt(0);
        sb.deleteCharAt(sb.length()-1);
        check(sb.toString());
    }
    else 
    {
        result = "The string is not a palindrome";
    }
    return result;
}

我尝试将几个字符串传递给此方法,包括回文。出于某种原因,它保持 returning 默认值“”。为什么方法 return 不提供有关字符串是否为回文的信息?

你必须在递归调用之前添加return。试试这个方法:

public static String check(String str)
{


    // Strips the string down to only letters a-z and numbers 0-9, and makes it lowercase
    str = str.replaceAll("[^A-Za-z0-9]", "");
    str = str.replaceAll("\s+","");
    str = str.toLowerCase();

    if (str.length() <= 1)
    {
        return ("The string is a palindrome" );


    }
    else if ((str.charAt(str.length() - 1)) == (str.charAt(0)))
    {
        StringBuilder sb = new StringBuilder(str);
        sb.deleteCharAt(0);
        sb.deleteCharAt(sb.length()-1);
        return check(sb.toString());
    }
    else
    {
        return "The string is not a palindrome";

    }
}