Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Trie {
- private:
- bool end;
- Trie* children[26];
- public:
- /** Initialize your data structure here. */
- Trie() {
- end = false;
- for(int i=0; i<26; i++)
- children[i] = NULL;
- }
- /** Inserts a word into the trie. */
- void insert(string word) {
- Trie *node = this;
- for(char c: word){
- c -= 'a';
- if(!node->children[c])
- node->children[c] = new Trie();
- node = node->children[c];
- }
- node->end = true;
- }
- /** Returns if there is any word in the trie that starts with the given prefix. */
- bool startsWith(vector<char> prefix) {
- Trie *node = this;
- for(char c: prefix){
- c -= 'a';
- if(!node->children[c])
- return false;
- node = node->children[c];
- if(node->end) return true;
- }
- return false;
- }
- };
- class StreamChecker {
- public:
- vector<char> str;
- Trie *root;
- int longLen = 0;
- StreamChecker(vector<string>& words) {
- root = new Trie();
- for(auto &word: words){
- longLen = max(longLen, int(word.length()));
- reverse(word.begin(), word.end());
- root->insert(word);
- }
- }
- bool query(char letter) {
- str.insert(str.begin(), letter);
- if(str.size() > longLen)
- str.pop_back();
- if(root->startsWith(str))
- 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);
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement