java - 递归方法不返回字符串
问题描述
我必须创建一个可以找到句子中包含的最长回文的代码。(例如,有些人喜欢蛋糕,但我更喜欢馅饼;最长的回文是我更喜欢 pi)。问题是在运行代码时它不会返回回文。我不确定问题是什么,但如果有人能弄清楚,我会很感激你让我知道。谢谢!
代码如下...
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();
}
}
解决方案
您忽略返回值。
例如:
recursion(word, currentLength, x, substring);
有一个返回值,好吧。你对递归调用什么都不做。从最外层调用返回的只是最外层调用的输入,它是一个空字符串。
您可能需要查看递归激活的工作原理。'return' 语句仅从当前级别返回,它不会清空整个调用堆栈。
推荐阅读
- r - R中是否有类似于Rust模式语法的东西?
- mql4 - IsTradeAllowed 没有返回我所期望的
- visual-studio-code - 有什么方法可以恢复我在 VS Code 中删除的设置?
- html - 如何停止浏览器缩放时更改 SVG 动画中心?
- javascript - 如何删除密文的“不需要”字节?
- javascript - 在 Vue.js + Firebase 中设置项目的更好方法是什么?
- node.js - 高 CPU 后 Postgres 进程突然停止?
- php - 如果图像在使用 PHP 的数据表中不可用,如何隐藏字段?
- c++ - 在硒的帮助下复制为卷曲
- python - 熊猫数据框分组和求和,组内,跨行值而不是按列