Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Most Efficient Algorithm to Find First Prefix-Match From a Sorted String Array?

Input:

1) A huge sorted array of string SA;

2) A prefix string P;

Output:

The index of the first string matching the input prefix if any. If there is no such match, then output will be -1.

Example:

SA = {"ab", "abd", "abdf", "abz"}
P = "abd"

The output should be 1 (index starting from 0).

What's the most algorithm way to do this kind of job?

like image 751
Morgan Cheng Avatar asked Jan 19 '09 10:01

Morgan Cheng


People also ask

How do you find the longest common prefix of an array?

The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not share any starting characters.

How do you find the prefix of a string in C++?

The match_results::prefix() is an inbuilt function in C++ which is used to get the string which is preceding the matched string in the input target string.

How do you find the common prefix of two strings in Java?

Given the array of strings S[], you need to find the longest string S which is the prefix of ALL the strings in the array. Longest common prefix (LCP) for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2. For Example: longest common prefix of “abcdefgh” and “abcefgh” is “ABC”.


1 Answers

If you only want to do this once, use binary search, if on the other hand you need to do it for many different prefixes but on the same string array, building a radix tree can be a good idea, after you've built the tree each look up will be very fast.

like image 74
Joe Lindström Avatar answered Sep 21 '22 05:09

Joe Lindström