648. Replace Words 替换单词
In English, we have a concept called root
, which can be followed by some other words to form another longer word - let's call this word successor
. For example, the root an
, followed by other
, which can form another word another
.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor
in the sentence with the root
forming it. If a successor
has many roots
can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
Example 1:
Input: dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat"
Note:
- The input will only have lower-case letters.
- 1 <= dict words number <= 1000
- 1 <= sentence words number <= 1000
- 1 <= root length <= 100
- 1 <= sentence words length <= 1000
在英语中,我们有一个叫做“根”的概念,可以用其他一些词来形成另一个更长的单词 - 让我们称之为“后继者”。例如,根an,其次是另一个词。
现在,给一个由许多根和一个句子组成的词典。你需要用形成它的根来替换句子中的所有后继者。如果后继有很多根可以形成它,用最短的根替换它。
现在,给一个由许多根和一个句子组成的词典。你需要用形成它的根来替换句子中的所有后继者。如果后继有很多根可以形成它,用最短的根替换它。
/**
* @param {string[]} dict
* @param {string} sentence
* @return {string}
*/
class Trie {
constructor() {
this.nodes = {};
}
insert(word) {
let node = this.nodes, cur;
for (let i = 0; i < word.length; i++) {
cur = word[i];
if (!node[cur]) {
node[cur] = {};
}
node = node[cur];
}
node.isWord = true;
}
match(prefix) {
let node = this.nodes, cur;
let res = ""
for (let i = 0; i < prefix.length; i++) {
cur = prefix[i];
if (!node[cur]) return null;
res += cur;
node = node[cur];
if (node.isWord) {
return res;
}
}
return res;
}
}
var replaceWords = function (dict, sentence) {
let tire = new Trie();
for (let i in dict) {
tire.insert(dict[i]);
}
let scentenctArr = sentence.split(/\s/);
for (let i in scentenctArr) {
let res = tire.match(scentenctArr[i])
if (res) {
scentenctArr[i] = res;
}
}
return scentenctArr.join(" ");
};
let dict = ["cat", "bat", "rat"];
let sentenct = "the cattle was rattled by the battery";
let res = replaceWords(dict, sentenct);
console.log(res);