Ruby's Louvre

每天学习一点点算法

导航

leetcode 648. Replace Words

将单词替换成其词根


function Node(value) {
      this.value = value
      this.word = null
      this.palindromes = []
      this.children = new Array(26)
    }
    class Tire {
      constructor() {
        this.root = new Node(null)
      }
      addWord(word) {
        var node = this.root;
        for (var i = 0; i < word.length; i++) {
          var next = word.charCodeAt(i) - 97
          if (!node.children[next]) {
            node.children[next] = new Node()
          }
          node = node.children[next]
        }
        node.word = word
      }
      replace(word) {
        var node = this.root;
        for (var c of word) {
          var next = c.charCodeAt(0) - 97;
          node = node.children[next]
          if (node) {
            if (node.word) {
              return node.word
            }
          } else {
            break
          }
        }
        return word;
      }
    }

    var replaceWords = function (dict, sentence) {
      var tire = new Tire();
      for (let word of dict) {
        tire.addWord(word)
      }
      return sentence.split(" ").map((word) => {
        return tire.replace(word)
      }).join(" ")

    };

    var dict = ["cat", "bat", "rat"]
    var sentence = "the cattle was rattled by the battery"
    console.log(replaceWords(dict, sentence))
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年

posted on 2019-12-27 21:43  司徒正美  阅读(203)  评论(0编辑  收藏  举报