leetcode 208. Implement Trie (Prefix Tree)

实现一个前缀树

function Node(value) {
      this.value = value
      this.passCount = 0;
      this.endCount = 0;
      this.children = {}
    }
    class Trie {
      constructor() {
        this.root = new Node(null)
      }
      insert(word) {
        var node = this.root;
        for (var c of word) {
          if (!node.children[c]) {
            node.children[c] = new Node(c)
          }
          node = node.children[c]
          node.passCount++
        }
        node.endCount++
      }
      search(word) {
        if (word === '') {
          return true
        }
        var node = this.root;
        for (var c of word) {
          node = node.children[c]
          if (!node) {
            return false
          }

        }
        return !!node.endCount
      }
      startWith(word) {
        if (word === '') {
          return true
        }
        var node = this.root;
        for (var c of word) {
          node = node.children[c]
          if (!node) {
            return false
          }
        }
        return cur !== this.root
      }
    }

你可能感兴趣的:(leetcode 208. Implement Trie (Prefix Tree))