编辑代码

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
  const sentences = (await readline())
    .split(/[,.;]/)
    .filter((sentence) => sentence !== "");
  const words = (await readline()).split(/[,.;]/).filter((word) => word !== "");
  console.log(getResult(sentences, words));
})();
const getResult = (sentences, words) => {
  // 将words中的单词放入集合中
  const wordSet = new Set(words);
  const ans = [];
  while (sentences.length > 0) {
    // 检查sentence中是否有单词在wordSet中
    const sentence = sentences.shift();
    // 从整个sentence开始检查
    let r = sentence.length;
    for (r; r > 0; r--) {
      // 若单词在wordSet中,则添加到ans中并从wordSet中删除,并检查sentence的截断中是否还有单词
      const newWord = sentence.slice(0, r);
      if (wordSet.has(newWord)) {
        ans.push(newWord);
        wordSet.delete(newWord);
        // 如果sentence中还有单词,将其添加到sentences的头部
        if (r < sentence.length) {
          sentences.unshift(sentence.slice(r));
        }
        break;
      }
    }
    if (r == 0) {
      // 若sentence中没有单词在wordSet中,输出sentence的首字母,并将sentence的剩下的单词放入sentences中
      ans.push(sentence[0]);
      sentences.unshift(sentence.slice(1));
    }
  }
  return ans.join(",");
};