题目1

image.png

题解

  1. var replaceWords = function(dictionary, sentence) {
  2. const dictionarySet = new Set();
  3. for (const root of dictionary) {
  4. dictionarySet.add(root);
  5. }
  6. const words = sentence.split(" ");
  7. for (let i = 0; i < words.length; i++) {
  8. const word = words[i];
  9. for (let j = 0; j < word.length; j++) {
  10. if (dictionarySet.has(word.substring(0, 1 + j))) {
  11. words[i] = word.substring(0, 1 + j);
  12. break;
  13. }
  14. }
  15. }
  16. return words.join(' ');
  17. };