문제: https://programmers.co.kr/learn/courses/30/lessons/12981
틀린다면 -> [틀린사람,틀린사람이 말한 횟수]를 출력
정확한 끝말잇기 -> [0,0] 출력
answer.push(word[i])
answer.includes(word[i])
로 비교한다.function solution(n, words) {
var answer = [];
for(let i=0; i<words.length; i++){
if(!answer.length) answer.push(words[i])
else{
if(checkChar(words[i-1],words[i])&&checkOverlap(answer,words[i])){
answer.push(words[i])
}else{
const who = (i+1)%n === 0 ? n : (i+1)%n
const turn = Math.ceil((i+1)/n)
return([who,turn])
}
}
}
return [0,0];
}
function checkChar(str1,str2){
return str1[str1.length-1]===str2[0]
}
function checkOverlap(arr,str){
return !arr.includes(str)
}
시간이 지나면서 더 간결하게 해결
function solution(n, words) {
const check = {};
let person = 1;
for (let i = 0; i < words.length; i++) {
if ((i !== 0 && words[i - 1].slice(-1) !== words[i][0]) || check[words[i]]) {
return [person, Math.ceil((i + 1) / n)];
}
person = person + 1 > n ? 1 : person + 1;
check[words[i]] = true;
}
return [0, 0];
}