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 somek >= 1
, the lastk
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.
struct Node{
vector<Node*> child = vector<Node*>(26 , NULL) ;
bool isword = false ;
} ;
class StreamChecker {
public:
StreamChecker(vector<string>& words) {
root = new Node() ;
addtree(root , words) ;
}
bool query(char letter) {
ans += string(1 , letter) ;
Node* p = root ;
for(int i = ans.size() - 1 ; i >= 0 ; --i)
{
if(p->child[ans[i] - 'a'] == NULL) return false ;
if(p->child[ans[i] - 'a']->isword) return true ;
p = p->child[ans[i] - 'a'] ;
}
return false ;
}
void addtree(Node* root , vector<string>& words)
{
for(int i = 0 ; i < words.size() ; ++i)
{
insert(root , words[i]) ;
}
}
void insert(Node* root , string &s)
{
Node* p = root ;
for(int i = s.size() - 1 ; i >= 0 ; --i)
{
if(p->child[s[i] - 'a'] == NULL)
{
p->child[s[i] - 'a'] = new Node() ;
}
p = p->child[s[i] - 'a'] ;
}
p->isword = true ;
}
private :
Node* root ;
string ans ;
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/