208. Implement Trie (Prefix Tree)
来源:互联网 发布:中央财经大学数据库 编辑:程序博客网 时间:2024/06/09 20:33
实现一个字典树
要求:
实现插入一个单词,查找一个单词,是否有某个前缀
思路:
不需要查找前缀单词的数目,也不需要删除一个单词。因此实现起来比较简单。字典树节点中只需要设置一个isEnd变量标记单词结束即可。
class TrieNode{ public: //因为这个题目不需要统计个数,不需要删除单词,所以,只设置结尾标志 TrieNode* next[26];//字典树的主要结构 bool isEnd;//当前节点是否是单词的结尾 TrieNode(bool is=false) { memset(next,0,sizeof(next)); isEnd=is; } };class Trie { TrieNode* root;public: /** Initialize your data structure here. */ Trie() { root=new TrieNode(); } /** Inserts a word into the trie. */ void insert(string word) { if(word.size()==0) return ; TrieNode* cur=root; for(int i=0;i<word.size();i++) { if(cur->next[word[i]-'a']==nullptr) cur->next[word[i]-'a']=new TrieNode(); cur=cur->next[word[i]-'a']; } cur->isEnd=true; } /** Returns if the word is in the trie. */ bool search(string word) { TrieNode* p=find(word); if(p==nullptr) return false; return p->isEnd; } /** Returns if there is any word in the trie that starts with the given prefix. */ //不需要返回前缀单词数目 bool startsWith(string prefix) { TrieNode* p=find(prefix); return p!=nullptr; } TrieNode* find(string s){ TrieNode* p=root; for(int i=0;i<s.size();i++) { if(p->next[s[i]-'a']==nullptr) return nullptr; p=p->next[s[i]-'a']; } return p;//返回这个指针,因为前面两个函数的应用不同 } };/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * bool param_2 = obj.search(word); * bool param_3 = obj.startsWith(prefix); */
阅读全文
0 0
- 208.Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- 208. Implement Trie (Prefix Tree)
- Regularization for DNN
- 80. Remove Duplicates from Sorted Array II
- 祭天时不同程序员的不同杀法
- 636. Exclusive Time of Functions
- 368. Largest Divisible Subset
- 208. Implement Trie (Prefix Tree)
- 机器学习课堂笔记6
- 代码生成代码,JavaBean Optional方式加强
- 单例模式解析
- 适配器多条目优化
- LibLinear(SVM包)使用说明之(一)README
- 645. Set Mismatch
- 从数据库取出数据在jsp页面上以表格形式呈现,并对表格数据进行分页打印操作。
- Calico 的网络结构是什么?- 每天5分钟玩转 Docker 容器技术(68)