[前缀树]leetcode1032:字符流(hard)

编程入门 行业动态 更新时间:2024-10-26 12:22:04

[<a href=https://www.elefans.com/category/jswz/34/1768815.html style=前缀树]leetcode1032:字符流(hard)"/>

[前缀树]leetcode1032:字符流(hard)

题目:

题解:
起初使用前缀树导致内存爆了,后改用后缀树顺利通过,不过就是时间有点吃不消了。(后缀树就是每个字符串反向后建立的前缀树,本质还是前缀树。

解题思路:

  • 1)从words中提取word,将word反向,建立后缀树。
  • 2)在查询的时候,我们将每个字符保存在一个字符串中,每次每个字符都插入到该字符串的首部。然后我们直接在后缀树中查找该字符串的最短前缀能否表示成一个字符串就行了。

代码如下:

class Trie{
private:bool is_string=false;Trie* next[26]={nullptr};
public:Trie(){}void insert(string& word){Trie* root=this;for(const auto& w:word){if(root->next[w-'a']==nullptr)root->next[w-'a']=new Trie();root=root->next[w-'a'];}root->is_string=true;}//word的最短前缀是否在后缀树中bool startsWith(string& word){Trie* root=this;for(const auto& w:word){if(root->next[w-'a']!=nullptr){root=root->next[w-'a'];if(root->is_string)return true;}else return false;}return false;}
};
class StreamChecker {
private:Trie* root;string word;
public:StreamChecker(vector<string>& words) {root=new Trie();for(auto word:words){reverse(word.begin(),word.end());//反向字符串root->insert(word);}}bool query(char letter) {Trie* note=root;word.insert(word.begin(),letter);//讲letter插入到word的前面return note->startsWith(word);}
};

更多推荐

[前缀树]leetcode1032:字符流(hard)

本文发布于:2023-07-28 18:51:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:前缀   字符   hard

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!