I've written this function that concats strings:
public void find(ArrayList<String> operations, ArrayList<String> set) {
String toMerge = operations.get(1);
String fromMerge = operations.get(2);
outer: for (int i = 0; i < set.size(); i++) {
String[] toSet = set.get(i).split(" ");
for (int k = 0; k < toSet.length; k++) {
if (toMerge.equals(toSet[k])) {
for (int j = 0; j < set.size(); j++) {
String[] fromSet = set.get(j).split(" ");
for (int x = 0; x < fromSet.length; x++) {
if (fromMerge.equals(fromSet[x])) {
for (int c = 0; c < toSet.length; c++) {
set.set(j, set.get(j)+ ' ' + toMerge.concat(' ' +toSet[c]));
set.set(i, " ");
}
break outer;
}
}
}
}
}
}
}
This function takes as parameter an arrayList
of operations, and an arrayList
of set:
For the
arrayList
ofoperations
, I always get a specific position, so I don't iterate. It is always \$O(1)\$.for the
arrayList
of set, I have to iterate, or rather, as I think of that to proceed:For example, if I have as operation
move foo bar
, I have to do these steps:First of all, I have to find where foo is:
Inside
set
, I can have this situation:position x : {bar tree hotel} ... position y : {foo lemon coffee}
When I find the string
foo
, I have to find the position ofbar
(I made an iteration as to findfoo
) and then i have to concat thefoo string into bar string
in this way:position x : {bar tree hotel foo lemon coffee} ... position y : {}
My program works as well as my function, but it is a nasty and inefficient solution. How can I improve the efficiency of this function?
.indexOf(String)
, then doing the concat with the index with.substring(index, yourString.length())
? \$\endgroup\$