递归回文函数保持返回默认结果值?

时间:2016-05-01 18:30:35

标签: java recursion palindrome

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;
}

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

1 个答案:

答案 0 :(得分:3)

您必须在递归调用之前添加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";

    }
}