排列编程挑战(Java)

时间:2016-07-18 16:06:11

标签: java arrays algorithm

好的,所以我有一个编程挑战,我试过解决自己,但我真的很挣扎。 首先,你有一个字符串数组(称为'单词'),每个字符串都是一个单词。

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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

以下是您问题的简单解决方案,
你的3ed循环有问题,你不需要它!

您只需循环浏览 start(i) end(j) 索引,如下所示:

public static void main(String[] args) {
    String search_query = "one two three";
    String[] queries = search_query.split(" ");

    List<String> liste = new ArrayList<>();

    for (int i = 0; i < queries.length; i++) {
        String query  = "";
        for (int j = i; j < queries.length; j++) {
            query  += queries[j] + " ";
            liste.add(query);
        }
    }

    for (String y : liste) {
        System.out.println(y);
    }
}