首页 > 解决方案 > 递归方法不返回字符串

问题描述

我必须创建一个可以找到句子中包含的最长回文的代码。(例如,有些人喜欢蛋糕,但我更喜欢馅饼;最长的回文是我更喜欢 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();
    }
}

标签: javapalindrome

解决方案


您忽略返回值。

例如:

       recursion(word, currentLength, x, substring);

有一个返回值,好吧。你对递归调用什么都不做。从最外层调用返回的只是最外层调用的输入,它是一个空字符串。

您可能需要查看递归激活的工作原理。'return' 语句仅从当前级别返回,它不会清空整个调用堆栈。


推荐阅读