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;
}
我尝试将几个字符串传递给此方法,包括回文。出于某种原因,它会一直返回默认值“”。为什么该方法不会返回有关该字符串是否为回文的信息?
答案 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";
}
}