Skip to content

Instantly share code, notes, and snippets.

@lishunan246
Created August 23, 2020 16:33
Show Gist options
  • Save lishunan246/cbbf45172eccd39d56f9b21c29225e0d to your computer and use it in GitHub Desktop.
Save lishunan246/cbbf45172eccd39d56f9b21c29225e0d to your computer and use it in GitHub Desktop.
1032. Stream of Characters
struct Node {
Node* children[26];
int flag;
Node() {
memset(children, 0, sizeof(children));
flag = 0;
}
};
class StreamChecker {
Node* root = nullptr;
std::unordered_set<Node*> s, tmp_s;
std::string target;
public:
StreamChecker(vector<string>& words) {
root = new Node();
for (auto& word : words) {
std::reverse(word.begin(), word.end());
auto p = root;
for (auto c : word) {
if (p->children[c-'a'] == nullptr) {
p->children[c-'a'] = new Node();
}
p = p->children[c-'a'];
}
p->flag = 1;
}
s.reserve(2000);
tmp_s.reserve(2000);
}
bool query(char letter) {
target.push_back(letter);
auto cur = root;
for (int i = target.size() - 1; i >= 0; --i) {
auto c = target[i];
if (cur->children[c-'a'] == nullptr) {
return false;
} else {
cur = cur->children[c-'a'];
if (cur->flag == 1) {
return true;
}
}
}
return false;
}
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment