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;
}
我尝试将多个字符串传递到此方法中,包括回文。由于某种原因,它不断返回默认值“”。为什么该方法不返回有关字符串是否为回文的信息?
最佳答案
递归调用前必须添加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";
}
}
关于java - 递归回文函数不断返回默认结果值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36970368/