[Algorithm] Trie data structure

博客探讨了存储数据并便于搜索的最佳数据结构,提出可使用Trie数据结构,它是一种非二叉树的树结构。还介绍了根据示例数组数据构建树的情况,以及用JavaScript实现的思路,如使用Map数据结构处理节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

For example we have an array of words:

[car, done, try, cat, trie, do]

What is the best data structure to store the data and easy for search? 

 

We can use Trie data structure, it is a tree, but not a binary tree. The reuslts of constructing a tree by using the example array data.

True of False means whether this letter is the last of the word.

 

We can code it by Javascript:

  • We are using Map data structure
  • If there is no existing node for giving letter, we create a new Node.
  • If there is a existing node, then we continue to next letter
function Node() {
  return {
    keys: new Map(),
    isWord: false
  };
}

function BuildTrie() {
  const root = new Node();
  return {
    root,
    add(word, node = this.root) {
      if (word.length === 0) {
        node.isWord = true;
        return;
      }
      const [head, ...rest] = word;
      if (!node.keys.has(head)) {
        node.keys.set(head, new Node());
      }

      return this.add(rest, node.keys.get(head));
    },
    hasWord(word, node = this.root) {
      if (!word) {
        return false;
      }
      while (word.length > 1) {
        if (!node.keys.has(word[0])) {
          return false;
        } else {
          node = node.keys.get(word[0]);
          word = word.substr(1);
        }
      }
      return node.keys.has(word) && node.keys.get(word).isWord;
    },
    print() {
      let words = [];
      function search(node = this.root, string = "") {
        if (node.keys.size != 0) {
          for (let letter of node.keys.keys()) {
            search(node.keys.get(letter), string.concat(letter));
          }
          if (node.isWord) {
            words.push(string);
          }
        } else {
          string.length > 0 ? words.push(string) : undefined;
        }
      }

      search(this.root, "");
      return words.length > 0 ? words : null;
    }
  };
}

const t = new BuildTrie();

t.add("cat");
t.add("cal");

console.log(t.hasWord("cat")); // true
console.log(t.hasWord("catt")); // false

  

 

转载于:https://www.cnblogs.com/Answer1215/p/10545262.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值