LeetCode 1032. Stream of Characters 4行Trie树

Implement the StreamChecker class as follows:

  • StreamChecker(words): Constructor, init the data structure with the given words.
  • query(letter): returns true if and only if for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.

 

Example:

StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary.
streamChecker.query('a');          // return false
streamChecker.query('b');          // return false
streamChecker.query('c');          // return false
streamChecker.query('d');          // return true, because 'cd' is in the wordlist
streamChecker.query('e');          // return false
streamChecker.query('f');          // return true, because 'f' is in the wordlist
streamChecker.query('g');          // return false
streamChecker.query('h');          // return false
streamChecker.query('i');          // return false
streamChecker.query('j');          // return false
streamChecker.query('k');          // return false
streamChecker.query('l');          // return true, because 'kl' is in the wordlist

 

Note:

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 2000
  • Words will only consist of lowercase English letters.
  • Queries will only consist of lowercase English letters.
  • The number of queries is at most 40000.

----------------------------

有几个值得学习的地方:

  • 逆序,需要脑筋急转弯
  • reduce函数,reduce函数可以放三个参数(https://blog.csdn.net/taoqick/article/details/112157779)
  • 当实例对象通过[] 运算符取值时,会调用它的方法__getitem__;也可以用在对象的迭代上。defaultdict.__getitem__(dic, 5)有两个参数,分别是dict的实例和key。
  • 别忘了剪枝

以下是代码:

from collections import defaultdict
class StreamChecker:

    def __init__(self, words: List[str]):
        add_child = lambda: defaultdict(add_child)
        self.trie = defaultdict(add_child)
        for word in words:
            reduce(dict.__getitem__,word[::-1],self.trie)["$"] = True
        self.history,self.max_len = "",max(map(len,words))

    def query(self, letter: str) -> bool:
        self.history = letter + self.history[:self.max_len-1]
        node = self.trie
        for ch in self.history:
            if ch not in node:
                return False
            else:
                node = node[ch]
                if ("$" in node):
                    return True
        return False


# Your StreamChecker object will be instantiated and called as such:
# obj = StreamChecker(words)
# param_1 = obj.query(letter)

 

你可能感兴趣的:(python3,leetcode)