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

 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. };






posted @ 2017-12-14 22:23  xiejunzhao  阅读(151)  评论(0)    收藏  举报