Ruby's Louvre

每天学习一点点算法

导航

leetcode 720. Longest Word in Dictionary

使用前缀树

 function Node() {
      this.word = ''
      this.children = {}
    }
    class Trie {
      constructor() {
        this.root = new Node()
      }
      addWord(word) {
        var node = this.root;
        for (let next of word) {

          if (!node.children[next]) {
            node.children[next] = new Node()
          }
          node = node.children[next]
        }
        node.word = word;
      }
      search(word) {
        var node = this.root;
        for (let c of word) {
          if (!node.children[c] || !node.children[c].word) {
            return false
          }
          node = node.children[c]
        }
        return true
      }
    }


    var longestWord = function (words, k) {
      if (!words.length) {
        return ''
      }
      var tire = new Trie;
      for (let word of words) {
        tire.addWord(word)
      }
      var ret = ''
      for (let word of words) {
        if (tire.search(word)) {
          if (word.length > ret.length) {
            ret = word;//更新最长单词
          } else if (word.length === ret.length && word.localeCompare(ret) < 0) {
            ret = word
          }
        } else { //过滤掉单词的前缀部分
          //  console.log("----", word) //不懂
        }
      }
      return ret;
    };

   console.log(longestWord(["ogz", "eyj", "e", "ey",
      "hmn", "v", "hm", "ogznkb", "ogzn", "hmnm",
      "eyjuo", "vuq", "ogznk", "og", "eyjuoi", "d"]
    ))

    console.log(longestWord(["w", "wo", "wor", "worl", "world"]))
    console.log(longestWord(["a", "banana", "app", "appl", "ap", "apply", "apple"]))

机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年

posted on 2019-12-28 22:35  司徒正美  阅读(177)  评论(0编辑  收藏  举报