码迷,mamicode.com
首页 > 其他好文 > 详细

208. Implement Trie (Prefix Tree) 实现前缀树

时间:2017-12-14 22:52:28      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:his   inpu   prototype   为知笔记   enum   int   tree   methods   var   

 Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z


  1. var Trie = function() {
  2. this.nodes = {};
  3. };
  4. Trie.prototype.insert = function(word) {
  5. let node = this.nodes, cur;
  6. for (let i = 0; i < word.length; i++) {
  7. cur = word[i];
  8. if (!node[cur]) {
  9. node[cur] = {};
  10. }
  11. node = node[cur];
  12. }
  13. node.isWord = true;
  14. };
  15. Trie.prototype.search = function(word) {
  16. let node = this.nodes, cur;
  17. for (let i = 0; i < word.length; i++) {
  18. cur = word[i];
  19. if (!node[cur]) {
  20. return false;
  21. }
  22. node = node[cur];
  23. }
  24. return node.isWord == true;
  25. };
  26. Trie.prototype.startsWith = function(prefix) {
  27. let node = this.nodes, cur;
  28. for (let i = 0; i < prefix.length; i++) {
  29. cur = prefix[i];
  30. if (!node[cur]) {
  31. return false;
  32. }
  33. node = node[cur];
  34. }
  35. return true;
  36. };






208. Implement Trie (Prefix Tree) 实现前缀树

标签:his   inpu   prototype   为知笔记   enum   int   tree   methods   var   

原文地址:http://www.cnblogs.com/xiejunzhao/p/8040330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!