gpt4 book ai didi

java - 帮助了解 Java 中的后向递归和 LinkedList

转载 作者:行者123 更新时间:2023-12-02 08:28:01 25 4
gpt4 key购买 nike

/**
* Converts linked list into a sentence (a single string representation).
* Each word pair is separated by a space. A period (".") is appended after
* the last word. The last link represents the first word in the sentence
* (and vice versa). The partialResult is the partial string constructed
* from earlier links. This partialResult is initially an empty string.
*/
public String getReversedSentence(String partialResult) {
if (next==null) {
partialResult+=this.word;
return partialResult + ".";
}
else{
partialResult=next.getReversedSentence(partialResult) + this.word;
return partialResult;
}
}

一切工作正常,除了句点(和空格,但我还不担心这一点)。我无法正确放置句号。

这是失败的测试:

public void testGetReversedSentence() {
LinkedList tail = new LinkedList("not",null);
LinkedList middle = new LinkedList("too",tail);
LinkedList head = new LinkedList("tricky",middle);
assertEquals("not.",tail.getReversedSentence(""));
assertEquals("not too tricky.",head.getReversedSentence(""));

它提出了not.tootricy而不是nottootootricky.

编辑:构造函数

public LinkedList(String word, LinkedList next) {
this.word = word;
this.next = next;
}

有什么提示吗?

最佳答案

嗯......没有必要使用 2 个方法,(重要)--> 因为这个方法有 StringpartialResult 作为参数。(如果你可以的话,你可以想要并且解决方案中是否允许辅助方法,但这是不必要的。)换句话说,尝试找到某种方法将当前单词与partialResult合并。另一个提示:有一个 3 行长的解决方案(并且格式正确)。

关于java - 帮助了解 Java 中的后向递归和 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4071340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com