首页 > 其他 > 详细

leetcode 648. Replace Words

时间:2019-12-27 23:02:42      阅读:105      评论:0      收藏:0      [点我收藏+]

将单词替换成其词根


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))

leetcode 648. Replace Words

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

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