Fastest possible string key lookup for known set of keys

后端 未结 8 2003
夕颜
夕颜 2020-12-30 04:26

Consider a lookup function with the following signature, which needs to return an integer for a given string key:

int GetValue(string key) { ... }

8条回答
  •  生来不讨喜
    2020-12-30 05:00

    Consider using Knuth–Morris–Pratt algorithm.

    Pre-process given map to a large string like below

    String string = "{foo:1}{bar:42}{bazz:314159}";
    int length = string.length();
    

    According KMP preprocessing time for the string will take O(length). For searching with any word/key will take O(w) complexity, where w is length of the word/key.

    You will be needed to make 2 modification to KMP algorithm:

    • key should be appear ordered in the joined string
    • instead of returning true/false it should parse the number and return it

    Wish it can give a good hints.

提交回复
热议问题