zoukankan      html  css  js  c++  java
  • 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"]))
    
    
  • 相关阅读:
    .NET的DTO映射工具AutoMapper
    使用TeamCity对项目进行可持续集成管理
    SpecFlow
    重构--改善既有代码的设计
    EntityFramework 7 开发纪录
    Solr索引
    DDD分层架构之值对象(层超类型篇)
    C#异步Socket示例
    Cnblogs API
    白鸦三次创业反思:公司遇问题 怎么走都对(转)
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/12113344.html
Copyright © 2011-2022 走看看