将单词替换成其词根
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))
原文:https://www.cnblogs.com/rubylouvre/p/12109753.html