LeetCode 实现 Trie (前缀树)

比眉伴天荒 2023-06-04 13:58 169阅读 0赞

题目链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/

题目大意:

  略。

分析:

  字典树模板.

代码如下:

ContractedBlock.gif ExpandedBlockStart.gif

  1. 1 class Trie {
  2. 2 public:
  3. 3 int passed; // 记录经过这个节点的字符串数量
  4. 4 int ends; // 记录有多少个字符串以这个节点结尾
  5. 5 unordered_map< char, Trie* > nxt;
  6. 6
  7. 7 /** Initialize your data structure here. */
  8. 8 Trie() {
  9. 9 passed = 0;
  10. 10 ends = 0;
  11. 11 }
  12. 12
  13. 13 /** Inserts a word into the trie. */
  14. 14 void insert(string word) {
  15. 15 Trie* p = this;
  16. 16 for(int i = 0; i < word.size(); ++i) {
  17. 17 if(p->nxt.find(word[i]) == p->nxt.end()) {
  18. 18 p->nxt[word[i]] = new Trie();
  19. 19 }
  20. 20 ++p->passed;
  21. 21 p = p->nxt[word[i]];
  22. 22 }
  23. 23 ++p->ends;
  24. 24 }
  25. 25
  26. 26 /** Returns if the word is in the trie. */
  27. 27 bool search(string word) {
  28. 28 Trie* p = this;
  29. 29 for(int i = 0; i < word.size(); ++i) {
  30. 30 if(p->nxt.find(word[i]) == p->nxt.end()) return false;
  31. 31 p = p->nxt[word[i]];
  32. 32 }
  33. 33 return p->ends != 0;
  34. 34 }
  35. 35
  36. 36 /** Returns if there is any word in the trie that starts with the given prefix. */
  37. 37 bool startsWith(string prefix) {
  38. 38 Trie* p = this;
  39. 39 for(int i = 0; i < prefix.size(); ++i) {
  40. 40 if(p->nxt.find(prefix[i]) == p->nxt.end()) return false;
  41. 41 p = p->nxt[prefix[i]];
  42. 42 }
  43. 43 return true;
  44. 44 }
  45. 45 };
  46. 46
  47. 47 /**
  48. 48 * Your Trie object will be instantiated and called as such:
  49. 49 * Trie* obj = new Trie();
  50. 50 * obj->insert(word);
  51. 51 * bool param_2 = obj->search(word);
  52. 52 * bool param_3 = obj->startsWith(prefix);
  53. 53 */

转载于:https://www.cnblogs.com/zaq19970105/p/11457612.html

发表评论

表情:
评论列表 (有 0 条评论,169人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Leetcode208. 实现 Trie (前缀)

    前言 蒟蒻做题。 已有工作 字典树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常