来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/replace-words 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

在英语中,我们有一个叫做 词根(root) 的概念,可以词根后面添加其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。
现在,给定一个由许多词根组成的词典 dictionary 和一个用空格分隔单词形成的句子 sentence。你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。
你需要输出替换之后的句子。

解答

  1. /**
  2. * @param {string[]} dictionary
  3. * @param {string} sentence
  4. * @return {string}
  5. */
  6. var replaceWords = function(dictionary, sentence) {
  7. dictionary = dictionary.sort((a, b) => a.length - b.length);
  8. const sentences = sentence.split(' ');
  9. const result = [];
  10. let i = 0, len = sentences.length;
  11. while (i < len) {
  12. const sen = sentences[i];
  13. let isHit = false;
  14. for (let j = 0; j < dictionary.length; j++) {
  15. const item = dictionary[j];
  16. if (sen.startsWith(item)) {
  17. isHit = true;
  18. result.push(item);
  19. break;
  20. }
  21. }
  22. if (!isHit) {
  23. result.push(sen);
  24. }
  25. ++i;
  26. }
  27. return result.join(' ');
  28. };