【发布时间】:2016-11-21 08:02:54
【问题描述】:
好的,所以我有一个编程挑战,我尝试过自己解决,但真的很挣扎。 首先,您有一个字符串数组(称为“单词”),每个字符串都是一个单词。
search_query = "these are all the words I start off with";
String[] queries = search_query.split(" ");
挑战是输出另一个数组,其中数组中的每个项目都是一个或多个单词长,并且该数组包含单词的每个排列,但保持单词的原始顺序,并且是连续的。 例如,这个字符串的数组:
"one two three"
应该是:
{"one", "one two", "one two three", "two", "two three", "three"}
这些项目最终的顺序并不重要,但是我会经常使用这个算法,所以效率有点重要。
(如果您想完全自己尝试,请剧透......)
这是我目前所有的代码:
search_query = "these are all the words I start off with";
String[] queries = search_query.split(" ");
ArrayList<String> final_list = new ArrayList<>();
String query;
for (int i = 0; i < queries.length; i++) { //i is the start index for one segment which will become a single item
for (int j = i; j < queries.length; j++) { //j is the end index for one segment which will become a single item
query = "";
for (int k = i; k < j; k++) {
//each item in final_list is made up from the items in queries from index i to k,
// where k <=j and k >=i
query += queries[k] + " ";
final_list.add(query);
}
}
}
【问题讨论】:
-
这些不是排列,而是子集之类的东西。此外,您的示例缺少“一,三”的情况。
-
“这些不是排列,而是子集之类的东西”我知道排列不是最好的词,但我不确定还能用什么。 “您的示例缺少“一,三”的情况。”:对不起,我进行了编辑,除了其他参数之外,我希望这些部分按连续顺序排列。
-
如果 n 是单词的数量,那么每个 n 位的二进制数代表一个解,其中 1 表示包含该单词,0 表示跳过该单词:1=001=3,2=010=2 , 3=011=二+三, 4=100=一, 5=101=一+三, 6=110=一+二, 7=111=一+二+三。