鱼C论坛

 找回密码
 立即注册
查看: 1892|回复: 0

[技术交流] C++刷leetcode(208. 实现 Trie (前缀树))【字典树】

[复制链接]
发表于 2020-6-8 10:15:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

  2. 示例:

  3. Trie trie = new Trie();

  4. trie.insert("apple");
  5. trie.search("apple");   // 返回 true
  6. trie.search("app");     // 返回 false
  7. trie.startsWith("app"); // 返回 true
  8. trie.insert("app");   
  9. trie.search("app");     // 返回 true
  10. 说明:

  11. 你可以假设所有的输入都是由小写字母 a-z 构成的。
  12. 保证所有输入均为非空字符串。

  13. 来源:力扣(LeetCode)
  14. 链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
  15. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. class Trie {
  2. private:
  3.     bool isEnd;
  4.     Trie* next[26];
  5. public:
  6.     /** Initialize your data structure here. */
  7.     Trie() {
  8.         isEnd = false;
  9.         memset(next, 0, sizeof(next));
  10.     }
  11.    
  12.     /** Inserts a word into the trie. */
  13.     void insert(string word) {
  14.         Trie*node = this;
  15.         for(auto cha : word){
  16.             if(node -> next[cha - 'a'] == NULL){
  17.                 node -> next[cha - 'a'] = new Trie();
  18.             }
  19.             node = node -> next[cha - 'a'];
  20.         }
  21.         node -> isEnd = true;
  22.     }
  23.    
  24.     /** Returns if the word is in the trie. */
  25.     bool search(string word) {
  26.         Trie*node = this;
  27.         for(auto cha : word){
  28.             if(node -> next[cha - 'a'] == NULL){
  29.                 return false;
  30.             }
  31.             node = node -> next[cha - 'a'];
  32.         }
  33.         return node ->isEnd;

  34.     }
  35.    
  36.     /** Returns if there is any word in the trie that starts with the given prefix. */
  37.     bool startsWith(string prefix) {
  38.         Trie*node = this;
  39.         for(auto cha : prefix){
  40.             if(node -> next[cha - 'a'] == NULL){
  41.                 return false;
  42.             }
  43.             node = node -> next[cha - 'a'];
  44.         }
  45.         return true;
  46.     }
  47. };

  48. /**
  49. * Your Trie object will be instantiated and called as such:
  50. * Trie* obj = new Trie();
  51. * obj->insert(word);
  52. * bool param_2 = obj->search(word);
  53. * bool param_3 = obj->startsWith(prefix);
  54. */
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-3 13:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表