tire前缀字典树javascript版本

17 阅读1分钟
  class Node {
        constructor(isWord = false) {
          this.isWord = isWord;
          this.next = new Map();
        }
      }

      class Tire {
        constructor() {
          this.root = new Node();
          this.size = 0;
        }
        insert(word) {
          let cur = this.root;
          for (let i = 0; i < word.length; i++) {
            const char = word[i];
            if (!cur.next.has(char)) {
              cur.next.set(char, new Node());
            }
            cur = cur.next.get(char);
          }

          if (!cur.isWord) {
            cur.isWord = true;
            this.size++;
          }
          return this;
        }
        inserts(words = []) {
          for (let word of words) {
            this.insert(word);
          }
          return this;
        }
        contains(word) {
          let cur = this.root;
          for (let i = 0; i < word.length; i++) {
            const char = word[i];
            if (!cur.next.has(char)) {
              return false;
            }
            cur = cur.next.get(char);
          }

          return cur.isWord;
        }
        delete(word) {
          let cur = this.root;
          for (let i = 0; i < word.length; i++) {
            const char = word[i];
            if (!cur.next.has(char)) {
              return false;
            }
            cur = cur.next.get(char);
          }
          cur.isWord = false;
          this.size--;
          return this;
        }

        finds(prefix) {
          let cur = this.root;
          for (let i = 0; i < prefix.length; i++) {
            const char = prefix[i];
            if (!cur.next.has(char)) {
              return [];
            }
            cur = cur.next.get(char);
          }

          const words = [];

          const dfs = (node, cur = "") => {
            for (let [char, next] of node.next) {
              dfs(next, cur + char);
            }

            if (node.isWord) {
              words.push(prefix + cur);
              return;
            }
          };

          dfs(cur);
          return words;
        }

        isPrefix(word) {
          let cur = this.root;
          for (let i = 0; i < word.length; i++) {
            const char = word[i];
            if (!cur.next.has(char)) {
              return false;
            }
            cur = cur.next.get(char);
          }
          return true;
        }

        getSize() {
          return this.size;
        }
      }

      const tire = new Tire();
      tire.inserts(["cat", "dog", "dogs", "door", "deer", "deers", "panda"]);
      tire.delete("panda");
      tire.insert("panda");
      console.log(tire.finds("panda"));

      console.log(tire.getSize());