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))
上一篇:自然语言处理(NLP)之命名实体识别


下一篇:C#练习题答案: 停止gninnipS我sdroW!【难度:2级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战