I have a program that makes operations on strings and this is the principal function of one of those operations. This works perfectly, but it is not efficient:
private void printString(ArrayList<String> operations, ArrayList<String> set) {
int numerOfStrings = 0;
int numberOfletters = 0;
String toPrint = operations.get(1);
outOfLoop: for (int i = 0; i < set.size(); i++) {
String[] toFind = set.get(i).split(" ");
for (int k = 0; k < toFind.length; k++) {
if (toPrint.equals(toFind[k])) {
String[] splited = set.get(i).split(" ");
for (int j = 0; j < splited.length; j++) {
numberOfletters += splited[j].length();
}
numerOfStrings = splited.length;
break outOfLoop;
}
}
}
System.out.println(numerOfStrings + " " + numberOfletters);
}
Explanation:
This function takes as parameter an arrayList
of operations, and an arrayList
of set:
For the
arrayList
ofoperations
, I get always 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 have as operation
print foo
, I have to do these steps:First of all, I have to find where foo is:
Inside
set
, I can have this situation:position 1 : {car tree hotel} ... position n : {foo lemon coffee}
When I find the string
foo
, I have to print the number of strings inside that position and the number of letters of each string, so in this case, I will print:3(number of strings) 14(sum of number of letters)
My program works as well as this function, but it is a nasty and inefficient solution. How can I improve the efficiency of my program?
oo
should he also give position n?(your code do but I suspect that may not be the case). Also your use case says number of letters of each string. Shouldn't be that 3 - 4 - 6? \$\endgroup\$