【leetcode】1032. Stream of Characters

题目如下:

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.

解题思路:本题真对不起hard的级别,用字典树即可解决。首先在init的时候,把words中所有word逆置后存入字典树中;在query的时候,也有逆序的方式记录所有历史query过的值,同时判断其前缀是否存在于字典树中即可。

代码如下:

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.childDic = {}
        self.isword = False

class Trie(object):
    dic = {}
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TreeNode(None)
        self.dic = {}

    def insert(self,word):
        node = self.root
        for i in word:
            if i not in node.childDic:
                node.childDic[i] = TreeNode(i)
            node = node.childDic[i]
        node.isword = True
    def isExist(self,word):
        node = self.root
        for i in word:
            if i in node.childDic:
                node = node.childDic[i]
                if node.isword == True:
                    return True
            else:
                return False


class StreamChecker(object):
    q = ''
    def __init__(self, words):
        """
        :type words: List[str]
        """
        self.t = Trie()
        for w in words:
            self.t.insert(w[::-1])


    def query(self, letter):
        """
        :type letter: str
        :rtype: bool
        """
        #letter = letter[::-1]
        self.q = letter + self.q
        return self.t.isExist(self.q)
原文地址:https://www.cnblogs.com/seyjs/p/10765511.html