This question only concerns the algorithm. In pseudocode, it looks like this:
A = Array of strings;
S = String to find;
for (Index=0; Index<count(A); Index++)
if (A[Index]==S) {
print "First occurrence at index\x20"+Index;
break;
}
For for loop requires string comparison N times (or byte comparison N * M times, O (N * M)). This is bad when array A has many elements or when string S is too long.
Any best way to find out the first occurrence? Some algorithm in O (K * logK) is fine, but preferable in O (K) or best of all in O (logK), where K is either N or M.
I don't mind adding to some other structures or doing some data processing before the comparison cycle.
source
share