The fastest algorithm for finding a string in an array of strings?

This question only concerns the algorithm. In pseudocode, it looks like this:

A = Array of strings; //let say count(A)  = N
S = String to find;   //let say length(S) = M

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.

+5
source share
5 answers

, , . .

+3

, , , , .

+3

, O (m * nlogn). A , O (m * logn).

, . , Java 2 :

Arrays.sort(A);
int index = Arrays.binarySearch(A, "S");
+2

. O (log (n)) O (log (n)) .

, - , - , O (1) O (1) - . - , O (n) O (n) .

+2

- , , ,

(, Quicksort, O (NlogN)), O (log (N))

+1
source

All Articles