[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

  

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10545262.html