Trie
因为是求后缀,我们可以预处理的时候把words中的单词逆序建立字典树,同时记录单词结点的结尾位置。求字符流的后缀直接在字典树中查找即可,找到单词结尾位置的结点,说明存在某个后缀是words中的单词,返回即可。
class StreamChecker {
public:
int ch[400010][26];
int idx;
unordered_set<int> st;
char wd[40010];
int c;
void insert(string s){
int p=0;
for(int i=0;i<s.size();i++){
int j=s[i]-'a';
if(!ch[p][j]) ch[p][j]=++idx;
p=ch[p][j];
}
st.insert(p);
}
bool query(){
int p=0;
for(int i=c-1;~i;i--){
int j=wd[i]-'a';
if(!ch[p][j]) return 0;
if(st.count(ch[p][j])) return 1;
p=ch[p][j];
}
return 0;
}
StreamChecker(vector<string>& words) {
memset(ch,0,sizeof ch);
for(auto c:words){
reverse(c.begin(),c.end());
insert(c);
}
}
bool query(char letter) {
wd[c++]=letter;
return query();
}
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/
时间复杂度:O(nL+qL),n为words的长度,L为字符串中的最大单词的长度,q为询问次数。
空间复杂度:O(nL)。

本文介绍了一种利用字典树(Trie)的数据结构来高效处理字符流的后缀匹配问题。通过逆序插入单词并记录结尾位置,可以实现实时查询字符流是否包含已知单词作为其后缀。
322

被折叠的 条评论
为什么被折叠?



