个人认为,面试时候将Trie写成结构体方便面试官理解一点,提供一个自己的解法
class StreamChecker {
public:
struct Trie{
unordered_map<char,Trie*> child;
bool flag;
};
string checkStr;
Trie* root;
void insert(string &s){
reverse(s.begin(),s.end());
auto cur=root;
for (auto &c:s){
if (!cur->child.count(c)) cur->child[c]=new Trie();
cur=cur->child[c];
}
cur->flag=true;
}
StreamChecker(vector<string>& words) {
root=new Trie();
for (auto &s:words)
insert(s);
}
bool query(char letter) {
checkStr+=letter;
auto cur=root;
for (int i=checkStr.size()-1;i>=0;i--){
char ch=checkStr[i];
if (!cur->child.count(ch)) return false;
cur=cur->child[ch];
if (cur->flag) return true;
}
return false;
}
};