gpt4 book ai didi

java - 使用递归将句子逐字添加到集合中

转载 作者:行者123 更新时间:2023-11-30 08:10:25 25 4
gpt4 key购买 nike

我正在尝试使用java中的递归将句子的每个单词添加到一个集合中。标点符号并不重要。

我的问题是打印列表后只打印句子的第一个单词。

例如,句子“一二三四”在我的列表中将显示为 [One]。

public static TreeSet<String> getWordSet(String words) {
TreeSet<String> result = new TreeSet<String>();
int index = words.indexOf(" ");

if (index < 0) {
return result;
} else {
result.add(words.substring(0, index));
getWordSet(words.substring(index + 1));
}
return result;
}

有什么我遗漏或忽略的吗?

最佳答案

你应该将递归函数的返回值的结果添加到你的结果集中,(而且你没有考虑最后一个词),像这样(我在评论中给出解释)

public static TreeSet<String> getWordSet(String words) {
TreeSet<String> result = new TreeSet<String>();
int index = words.indexOf(" ");

if (index < 0 && words.length() == 0) {
return result;
}else if (index < 0 && words.length() > 0) { // here you didnt consider the last word
result.add(words);
} else {
result = getWordSet(words.substring(index + 1)); //here we first get result of recursion then add our new value to the list
result.add(words.substring(0, index));
}
return result;
}

关于java - 使用递归将句子逐字添加到集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30473512/

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