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 -1Note:
wordshas length in range[1, 15000].For each test case, up to
words.lengthqueriesWordFilter.fmay be made.words[i]has length in range[1, 10].prefix, suffixhave lengths in range[0, 10].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?