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:

  1. The input will only have lower-case letters.
  2. 1 <= dict words number <= 1000
  3. 1 <= sentence words number <= 1000
  4. 1 <= root length <= 100
  5. 1 <= sentence words length <= 1000 

在英语中,我们有一个叫做“根”的概念,可以用其他一些词来形成另一个更长的单词 - 让我们称之为“后继者”。例如,根an,其次是另一个词。
现在,给一个由许多根和一个句子组成的词典。你需要用形成它的根来替换句子中的所有后继者。如果后继有很多根可以形成它,用最短的根替换它。

  1. /**
  2. * @param {string[]} dict
  3. * @param {string} sentence
  4. * @return {string}
  5. */
  6. class Trie {
  7. constructor() {
  8. this.nodes = {};
  9. }
  10. insert(word) {
  11. let node = this.nodes, cur;
  12. for (let i = 0; i < word.length; i++) {
  13. cur = word[i];
  14. if (!node[cur]) {
  15. node[cur] = {};
  16. }
  17. node = node[cur];
  18. }
  19. node.isWord = true;
  20. }
  21. match(prefix) {
  22. let node = this.nodes, cur;
  23. let res = ""
  24. for (let i = 0; i < prefix.length; i++) {
  25. cur = prefix[i];
  26. if (!node[cur]) return null;
  27. res += cur;
  28. node = node[cur];
  29. if (node.isWord) {
  30. return res;
  31. }
  32. }
  33. return res;
  34. }
  35. }
  36. var replaceWords = function (dict, sentence) {
  37. let tire = new Trie();
  38. for (let i in dict) {
  39. tire.insert(dict[i]);
  40. }
  41. let scentenctArr = sentence.split(/\s/);
  42. for (let i in scentenctArr) {
  43. let res = tire.match(scentenctArr[i])
  44. if (res) {
  45. scentenctArr[i] = res;
  46. }
  47. }
  48. return scentenctArr.join(" ");
  49. };
  50. let dict = ["cat", "bat", "rat"];
  51. let sentenct = "the cattle was rattled by the battery";
  52. let res = replaceWords(dict, sentenct);
  53. console.log(res);






posted @ 2017-12-29 22:55  xiejunzhao  阅读(199)  评论(0编辑  收藏  举报