Formatted question description: https://leetcode.ca/all/1032.html

1032. Stream of Characters (Hard)

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.

Related Topics:
Trie

Solution 1. Trie

// OJ: https://leetcode.com/problems/stream-of-characters/

// Time:
//      StreamChecker: O(S)
//      query: O(Q)
// Space: O(S)
struct TrieNode {
    TrieNode *next[26] = {};
    bool end = false;
};
class StreamChecker {
    vector<TrieNode*> nodes;
    TrieNode root;
    void add(TrieNode *node, string &s) {
        for (char c : s) {
            if (node->next[c - 'a'] == NULL) node->next[c - 'a'] = new TrieNode();
            node = node->next[c - 'a'];
        }
        node->end = true;
    }
public:
    StreamChecker(vector<string>& words) {
        auto node = &root;
        for (auto &s : words) add(node, s);
    }
    bool query(char letter) {
        nodes.push_back(&root);
        int len = nodes.size();
        bool ans = false;
        for (int i = len - 1; i >= 0; --i) {
            auto &node = nodes[i];
            if (node->next[letter - 'a'] == NULL) swap(nodes[--len], nodes[i]);
            else {
                node = node->next[letter - 'a'];
                if (node->end) ans = true;
            }
        }
        nodes.resize(len);
        return ans;
    }
};

All Problems

All Solutions