class TrieNode {
public:
bool is_end;
vector<TrieNode*> children = vector<TrieNode*>(26, nullptr);
TrieNode() {
is_end = false; }
};
class StreamChecker {
public:
TrieNode* root = new TrieNode();
TrieNode* p;
queue<TrieNode*> Q;
void insert(string word) {
p = root;
for(int ii = 0; ii < word.size(); ii++) {
if(!p->children[word[ii] - 'a']) p->children[word[ii] - 'a'] = new TrieNode();
p = p->children[word[ii] - 'a'];
}
p->is_end = true;
}
StreamChecker(vector<string>& words) {
for(auto &word : words) insert(word);
}
bool query(char letter) {
bool flag = false;
int Q_len = Q.size();
for(int ii = 0; ii < Q_len; ii++) {
p = Q.front();
Q.pop();
if(p->children[letter - 'a']) {
Q.push(p->children[letter - 'a']);
if(p->children[letter - 'a']->is_end) flag = true;
}
}
if(root->children[letter - 'a']) {
Q.push(root->children[letter - 'a']);
if(root->children[letter - 'a']->is_end) flag = true;
}
return flag;
}
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/
[Leetcode辞書ツリー(プレフィックスツリー)C ++] 1032。文字のストリーム
おすすめ
転載: blog.csdn.net/m0_37454852/article/details/113775619
おすすめ
ランキング