我必须创建一个代码,可以找到最长的回文中包含的句子(有些人喜欢蛋糕,但我更喜欢馅饼;最长的回文是我喜欢π)。问题是在运行代码时它不会返回回文。我不知道问题出在哪里,但如果有人能解决的话,我希望你能告诉我。谢谢!
代码如下。。。
public class Recursion6 {
static String recursion(String word, int currentLength, int x, String substring) {
String reverse =new StringBuffer(word).reverse().toString();
if(word.length() == 1 ){
return substring;
}
if(word.charAt(0) != word.charAt(x)) {
if(x == word.length() - 1) {
recursion(word.substring(1), currentLength, 1, substring);
}
x++;
recursion(word, currentLength, x, substring);
} else {
if(word.substring(0, x + 1).equalsIgnoreCase(reverse.substring(word.length() - (x+1), word.length()))) {
if(word.substring(0, x).length() > currentLength) {
currentLength = word.substring(0, x + 1).length();
substring = word.substring(0, x + 1);
}
recursion(word.substring(1), currentLength, 1, substring);
}
recursion(word.substring(1), currentLength, 1, substring);
}
return substring;
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter a Sentence:");
String word=sc.nextLine();
System.out.println("The Palendrome is "+recursion(word.replaceAll(" ", ""), 1, 1, null));
sc.close();
}
}
2条答案
按热度按时间bvn4nwqk1#
忽略返回值。
例如:
有一个返回值,好吧。对于递归调用,你什么也不做。从最外层调用返回的只是最外层调用的输入,它是一个空字符串。
您可能需要回顾递归激活是如何工作的。“return”语句只从当前级别返回,不清空整个调用堆栈。
aiazj4mn2#
这是另一种方法。
首先,获取堆栈上的所有子字符串。前两个递归调用就是这样做的。
然后只要在堆栈展开时检查每个子字符串,看看它是否是回文。
私有方法执行实际检查。它只是比较字符的两端向中间。
最终输出可能包含空格和/或标点字符。
印刷品
该方法获取字符串、起始索引和结束索引。