置换编程挑战(Java) [英] Permutation programming challenge (Java)

查看:65
本文介绍了置换编程挑战(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我遇到了编程难题,虽然我尝试解决自己的问题,但确实很挣扎。
首先,您需要一个字符串数组(称为单词),每个字符串都是一个单词。

Ok, so I have a programming challenge which I have tried solving myself but am really struggling with. To start off you have an Array of Strings (called 'words'), each of these Strings is a single word.

search_query = "these are all the words I start off with";        
String[] queries = search_query.split(" ");

挑战是输出另一个数组,其中数组中的每个项目都长一个或多个单词,并且数组包含单词的每个排列,但使单词保持原始顺序以及连续的顺序。
例如,此字符串的数组:

The challenge is to output another array where each item in the array is one or more words long and the array contains every permutation of the words, but keeps the words in the original order, as well being consecutive. For example, the array for this string:

"one two three"

应该是:

{"one", "one two", "one two three", "two", "two three", "three"}

这些项目的最终排序并不重要,但是我将经常使用此算法,因此效率有些重要。

The order these items end up in is not important, however I am going to be going through this algorithm quite often so efficiency is somewhat important.

这是我到目前为止的全部代码:

Here is all my code I have so far:

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


推荐答案

这是您问题的简单解决方案,

您的3ed循环中有问题,您不需要它!

Here is a simple solution of your problem,
you have a problem in your 3ed loop, you don't need it!

您只需要遍历 start(i) end(j) 索引如下所示:

You just need to loop through your start(i) and end(j) indices as shown below:

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

这篇关于置换编程挑战(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆