Search for strings matching the pattern “abc:*:xyz” in less than O(n)

前端 未结 4 1031
有刺的猬
有刺的猬 2021-01-07 10:45

Given a bunch of strings I need to find those which match 3 kinds of patterns:

  • Prefix search - abc*
  • Glob-like pattern - abc:*:xyz
  • Suffix sear
4条回答
  •  旧时难觅i
    2021-01-07 11:37

    Generate rotations of each word and put each rotation in a suffix tree with indication of "rotation index'.

    For example, to put the string "hello", put

    hello, 0
    elloh, 1
    llohe, 2
    lohel, 3
    ohell, 4
    

    Also, you put "hero" as

    hero, 0
    eroh, 1
    rohe, 2
    oher, 3
    

    Also, you put "ohe" (don't ask me what's ohe)

    ohe, 0
    heo, 1
    eoh, 2
    

    Then, if you need to search for pattern "he*o", you need to rotate it until you get a prefixed string: "ohe*"

    In the suffix tree you find the candidates: (ohell, 4), (oher, 3), (ohe, 0). Then you restore their original versions (by un-rotating them) and pick the right ones - "hello" and "hero".

提交回复
热议问题