Prefix and Suffix Search(Trie)

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:

words has length in range [1, 15000].
For each test case, up to words.length queries WordFilter.f may be made.
words[i] has length in range [1, 10].
prefix, suffix have lengths in range [0, 10].
words[i] and prefix, suffix queries consist of lowercase letters only.

分析

1 建2个树,然后pre找pre树,suffix找suffix树,这里倒建倒查。容易超时。

2.insert'#apple', 'e#apple', 'le#apple', 'ple#apple', 'pple#apple', 'apple#apple'

into the trie. Then for a query likeprefix = "ap", suffix = "le", we can find it by querying our trie forle#ap

注意这里weight, 因为w是word的index,所以树里一个Node的w虽然一直被更新,但最新的w就是最后那个word的index,也就是最大的。

.Python

python children里存的是dict[c] = TrieNode() java是dict[index]一定要区别清楚

所以这里直接word是 w+#+w 然后遍历整个word, 每个char dict[char]

Last updated

Was this helpful?