【发布时间】:2021-04-21 16:35:39
【问题描述】:
我必须创建一个代码,可以找到句子中包含的最长回文。 (例如,有些人喜欢蛋糕,但我更喜欢馅饼;最长的回文是我更喜欢 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();
}
}
【问题讨论】:
-
最长回文子串,是你要问的吗?
-
最长的plaindrome包含在子字符串变量中。这个想法是,当程序完成搜索句子时,它会返回子字符串并打印它。我尝试使用 if(word.length() == 1) 来执行此操作,但它没有返回任何内容
-
与此问题相同的问题:Recursive method returning empty value,也许您从那里的答案中学到了一些东西,然后可以修复您的程序。
标签: java palindrome