zoukankan      html  css  js  c++  java
  • [Algorithm] Trie data structure

    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
    

      

  • 相关阅读:
    React antd的select框的onchange事件 只能点击一次 如果想选中的值 还可以被点击 就用onselect事件
    formatTime.js
    typeScript
    React react-router在url参数不同的情况下跳转页面不更新
    React 组件
    三、猜字符小游戏
    二、Java学习之方法
    Java学习之数组
    JavaWeb的学习--第五天 javascript03
    JavaWeb的学习--第四天 javascript02
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10545262.html
Copyright © 2011-2022 走看看