745. Prefix and Suffix Search

来源:互联网 发布:犀牛软件基础教程 编辑:程序博客网 时间:2024/06/07 22:53

Given many wordswords[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 0WordFilter.f("b", "") // returns -1

Note:

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

思路:用2个trie数,保存当前的前缀后缀对应的所有weight,然后求2个集合的交集

会TLE

import collectionsTrie = lambda: collections.defaultdict(Trie)weightSet = Falseclass 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])    


TLE的原因在于最后得到的2个集合could still be large, so we might TLE if we aren't careful.
考虑到题目说每个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 collectionsTrie = lambda: collections.defaultdict(Trie)WEIGHT = Falseclass 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]



阅读全文
0 0