[LeetCode] Stream of Characters

1032. Stream of Characters

Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words.

For example, if words = [“abc”, “xyz”] and the stream added the four characters (one by one) ‘a’, ‘x’, ‘y’, and ‘z’, your algorithm should detect that the suffix “xyz” of the characters “axyz” matches “xyz” from words.

Implement the StreamChecker class:

  • StreamChecker(String[] words) Initializes the object with the strings array words.
  • boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Trie {
Trie* next[26] = {};
bool eof;
public:
Trie(): eof(false) {};

void insert(string& w, int pos) {
if(pos == -1) eof = true;
else {
if(next[w[pos]-'a'] == nullptr) {
next[w[pos]-'a'] = new Trie();
}
next[w[pos]-'a']->insert(w, pos-1);
}
}
bool find(string& w, int pos) {
if(pos == -1 || eof) return eof;
if(next[w[pos]-'a'] == nullptr) return false;
return next[w[pos]-'a']->find(w, pos-1);
}
};

class StreamChecker {
string s;
Trie* trie;
public:
StreamChecker(vector<string>& words) {
this->trie = new Trie();
for(auto& w : words) {
trie->insert(w, w.length() - 1);
}
}

bool query(char letter) {
s += letter;
return trie->find(s, s.length() - 1);
}
};

/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/03/PS/LeetCode/stream-of-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.