클릭해서 문제 전체 보기🔼
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const [n, ...sentences] = fs
.readFileSync(filePath)
.toString()
.trim()
.split("\n");
let writing = sentences.pop().split(" ");
let sentenceArr = [];
let writingIdx = 0;
sentences.forEach((ele) => {
let sentence = ele.split(" ");
sentenceArr.push([sentence, 0, sentence.length]);
});
while (writingIdx < writing.length) {
let possibility = false;
sentenceArr.forEach((ele) => {
if (ele[1] == ele[2]) return;
let idx = ele[1];
while (
ele[0][idx] == writing[writingIdx] &&
writing[writingIdx] != undefined
) {
possibility = true;
writingIdx++;
idx++;
ele[1] = idx;
}
});
if (possibility === false) return console.log("Impossible");
}
for (i = 0; i < sentenceArr.length; i++) {
let sentence = sentenceArr[i];
if (sentence[1] != sentence[2]) return console.log("Impossible");
}
console.log("Possible");
📢 풀이 설명
문제 내용 해석
주어진 문장들 안의 단어들을 이용해, 문장의 순서의 상관없이 단어들만의 순서를 지키며 나열해서 마지막 문장을 만들수 있는지 여부를 판별하는 문제
풀이 내용은 각 문장의 idx를 늘려가며, 받아적은 문장의 단어와 비교하는 방법을 사용했다.
❗️ 이 문제에서 놓치기 쉬운 점은 "앵무새가 말한 단어를 다 받아적지 못한 경우"도 고려해야하는 것이다. ❗️
sentenceArr
에 [단어들, 현재 idx, 단어 개수] 순서대로 저장했다.possibility
라는 불린값을 만들어둔다.sentenceArr
를 한바퀴 돌며, 그것의 현재 idx에 해당하는 단어와 도는 단어의 Idx에 해당하는 단어가 일치하면 둘의 idx를 1 증가시킨다.이 문제는 사용한 단어를 앞에서부터 없애는 것이기 때문에 선입선출 구조라고 볼 수 있다.
따라서 큐 알고리즘
을 사용했다.