Created
August 23, 2020 16:33
-
-
Save lishunan246/cbbf45172eccd39d56f9b21c29225e0d to your computer and use it in GitHub Desktop.
1032. Stream of Characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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