首页 > 其他 > 详细

leetcode 720. Longest Word in Dictionary

时间:2019-12-28 23:51:22      阅读:142      评论:0      收藏:0      [点我收藏+]

使用前缀树

 function Node() {
      this.word = ''
      this.children = {}
    }
    class Tire {
      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 Tire;
      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"]))

leetcode 720. Longest Word in Dictionary

原文:https://www.cnblogs.com/rubylouvre/p/12113344.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!