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

前端 未结 8 721
春和景丽
春和景丽 2021-01-31 00:27

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 ther

8条回答
  •  礼貌的吻别
    2021-01-31 00:31

    My solution: Used binary search.

    private static int search(String[] words, String searchPrefix) {
    
            if (words == null || words.length == 0) {
                return -1;
            }
            int low = 0;
            int high = words.length - 1;
            int searchPrefixLength = searchPrefix.length();
    
            while (low <= high) {
                int mid = low + (high - low) / 2;
    
                String word = words[mid];
                int compare = -1;
    
                if (searchPrefixLength <= word.length()) {
                    compare = word.substring(0, searchPrefixLength).compareTo(searchPrefix);
                }
    
                if (compare == 0) {
                    return mid;
                } else if (compare > 0) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
    
            }
            return -1;
        }
    

提交回复
热议问题