题目描述:
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.
class TrieNode{
public:
bool isWord;
vector<TrieNode*> children;
TrieNode()
{
isWord=false;
children=vector<TrieNode*>(26,NULL);
}
};
class StreamChecker {
public:
StreamChecker(vector<string>& words) {
max_length=0;
root=new TrieNode();
for(string& word:words)
{
max_length=max(max_length,(int)word.size());
insert(word);
}
}
bool query(char letter) {
q.push_back(letter); // 累积字符串
while(q.size()>max_length) q.pop_front();
TrieNode* p=root;
stack<char> s; // 由于不确定一共遍历了多少个字符,用一个栈对队列进行恢复
bool result=false;
while(!q.empty())
{
int j=q.back()-'a';
q.pop_back();
s.push('a'+j);
if(p->children[j]==NULL) break;
else if(p->children[j]->isWord)
{
result=true;
break;
}
p=p->children[j];
}
recover_deque(s);
return result;
}
void insert(string& s)
{
TrieNode* p=root;
for(int i=s.size()-1;i>=0;i--) // 倒序把单词插入,累积的字符串也是倒序查询
{
int j=s[i]-'a';
if(p->children[j]==NULL) p->children[j]=new TrieNode();
p=p->children[j];
}
p->isWord=true;
}
void recover_deque(stack<char>& s)
{
while(!s.empty())
{
q.push_back(s.top());
s.pop();
}
}
private:
TrieNode* root;
int max_length;
deque<char> q; // 双向队列用来保留max_length个字符
};