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"
Should be:
{"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.
(Spoilers if you want to try it entirely yourself...)
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);
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…