Given many words
, words[i]
has weight i
.
Design a class WordFilter
that supports one function, WordFilter.f(String prefix, String suffix)
. It will return the word with given prefix
and suffix
with 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
queriesWordFilter.f
may be made. words[i]
has length in range[1, 10]
.prefix, suffix
have lengths in range[0, 10]
.words[i]
andprefix, suffix
queries consist of lowercase letters only.
思路:用2个trie数,保存当前的前缀后缀对应的所有weight,然后求2个集合的交集
会TLE
import collections
Trie = lambda: collections.defaultdict(Trie)
weightSet = False
class WordFilter:
def __init__(self, words):
"""
:type words: List[str]
"""
self.trie1 = Trie()
self.trie2 = Trie()
for weight, word in enumerate(words):
cur = self.trie1
if weightSet not in cur: cur[weightSet]=set()
cur[weightSet].add(weight)
for w in word:
cur = cur[w]
if weightSet not in cur: cur[weightSet]=set()
cur[weightSet].add(weight)
cur = self.trie2
if weightSet not in cur: cur[weightSet]=set()
cur[weightSet].add(weight)
for w in word[::-1]:
cur = cur[w]
if weightSet not in cur: cur[weightSet]=set()
cur[weightSet].add(weight)
def f(self, prefix, suffix):
"""
:type prefix: str
:type suffix: str
:rtype: int
"""
cur1 = self.trie1
for w in prefix:
if w not in cur1: return -1
cur1 = cur1[w]
cur2 = self.trie2
for w in suffix[::-1]:
if w not in cur2: return -1
cur2 = cur2[w]
return max(cur1[weightSet] & cur2[weightSet])
考虑到题目说每个word的length很小,长度最多为10
For each suffix of the word, we could insert that suffix, followed by '#'
, followed by the word, all into the trie.
For example, we will insert '#apple', 'e#apple', 'le#apple', 'ple#apple', 'pple#apple', 'apple#apple'
into the trie. Then for a query like prefix = "ap", suffix = "le"
, we can find it by querying our trie for le#ap
.
这样我们就只要遍历一遍Trie树就好啦,而且增加的words数目也不会很多
import collections
Trie = lambda: collections.defaultdict(Trie)
WEIGHT = False
class WordFilter:
def __init__(self, words):
self.trie = Trie()
for weight, word in enumerate(words): # for every single word
word += '#'
for i in range(len(word)): # for every augmented word
cur = self.trie
cur[WEIGHT] = weight # cur prefix max weight, since weight is increasing
for j in range(i, 2*len(word)-1): # for every bit of augmented word, start from apple#apple
cur = cur[word[j%len(word)]]
cur[WEIGHT] = weight
def f(self, prefix, suffix):
cur = self.trie
for w in suffix+'#'+prefix:
if w not in cur: return -1
cur = cur[w]
return cur[WEIGHT]