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

Posted Long Long Journey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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. };






以上是关于208. Implement Trie (Prefix Tree) 实现前缀树的主要内容,如果未能解决你的问题,请参考以下文章

208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

[LeetCode] 208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)