745 Prefix and Suffix Search

1. Question

Given manywords,words[i]has weighti.

Design a classWordFilterthat supports one function,WordFilter.f(String prefix, String suffix). It will return the word with givenprefixandsuffixwith maximum weight. If no word exists, return -1.

Examples:

Input:

WordFilter(["apple"])
WordFilter.f("a", "e") // returns 0
WordFilter.f("b", "") // returns -1

Note:

  1. wordshas length in range[1, 15000].

  2. For each test case, up towords.lengthqueriesWordFilter.fmay be made.

  3. words[i]has length in range[1, 10].

  4. prefix, suffixhave lengths in range[0, 10].

  5. words[i]andprefix, suffixqueries consist of lowercase letters only.

2. Implementation

(1) HashMap

(2) Trie

思路: 利用trie的特性,将suffix + "#" + prefix作为key插入trie里,并以此作为查询的key

3. Time & Space Complexity

HashMap: 时间复杂度O(nl^2), n是word的个数, l是word的平均长度, 空间复杂度O(nl^2)

Trie: 时间复杂度O(nl^2), n是word的个数, l是word的平均长度, 空间复杂度O(nl^2)

Last updated

Was this helpful?