745. Prefix and Suffix Search

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 0
WordFilter.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 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])
    


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 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]



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值