leetcode前缀树java_LeetCode 实现 Trie (前缀树)

题目大意:

略。

分析:

字典树模板.

代码如下:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 class Trie {

2 public:

3 int passed; // 记录经过这个节点的字符串数量

4 int ends; // 记录有多少个字符串以这个节点结尾

5 unordered_map< char, Trie* > nxt;

6

7 /** Initialize your data structure here. */

8 Trie() {

9 passed = 0;

10 ends = 0;

11 }

12

13 /** Inserts a word into the trie. */

14 void insert(string word) {

15 Trie* p = this;

16 for(int i = 0; i < word.size(); ++i) {

17 if(p->nxt.find(word[i]) == p->nxt.end()) {

18 p->nxt[word[i]] = new Trie();

19 }

20 ++p->passed;

21 p = p->nxt[word[i]];

22 }

23 ++p->ends;

24 }

25

26 /** Returns if the word is in the trie. */

27 bool search(string word) {

28 Trie* p = this;

29 for(int i = 0; i < word.size(); ++i) {

30 if(p->nxt.find(word[i]) == p->nxt.end()) return false;

31 p = p->nxt[word[i]];

32 }

33 return p->ends != 0;

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* p = this;

39 for(int i = 0; i < prefix.size(); ++i) {

40 if(p->nxt.find(prefix[i]) == p->nxt.end()) return false;

41 p = p->nxt[prefix[i]];

42 }

43 return true;

44 }

45 };

46

47 /**

48 * Your Trie object will be instantiated and called as such:

49 * Trie* obj = new Trie();

50 * obj->insert(word);

51 * bool param_2 = obj->search(word);

52 * bool param_3 = obj->startsWith(prefix);

53 */

View Code

来源:https://www.cnblogs.com/zaq19970105/p/11457612.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值