프로그래머스 - 영어 끝말잇기

front_pica·2021년 5월 15일
0

문제


풀이과정

  1. 현재 단어의 끝문자와 다음 단어의 첫문자를 비교, 다음단어가 이전에 나왔는지
    탈락자가 생기지 않을때 이 세가지 처리를 해주어야한다.

  2. 위의 처리를 해주기 위해 count(몇번째 사람인지) whatTimes(몇번 반복되었는지)
    tempArr(각 사람의 현재 외친 단어) stackArr(사람들이 여태까지 외친 단어들)
    이렇게 변수를 지정해서 나타내주고 boom 변수는 탈락자가 생기지 않는 상황을 위해 true false로 지정해 주었다.

  3. for문을 words길이만큼 돌면서 현재단어와 다음 올 단어를 각각 비교해서 count와 whatTimes를 적절하게 증가시켜주면 된다.

코드

function solution(n, words) {
  const tempArr = [];
  const stackArr = [];
  let count = 0;
  let whatTimes = 1; //시작할때부터 1번으로 치기때문에 1로 선언
  let boom = false;

  //맨처음은 비교할게 없으니 그냥 넣어주고 count 증가
  tempArr[0] = words[0];
  stackArr[0] = words[0];
  count++;

  for(let i = 0; i < words.length -1; i ++) {
    if(count === n) {
      count = 0;
      whatTimes++;
    }

    if(words[i][words[i].length -1] === words[i+1][0]) {
      if(stackArr.includes(words[i+1])) {
        count++;
        boom = true;
        break;
      }

      stackArr.push(words[i+1]);
      tempArr[count] = words[i+1];
      count++;
    } else {
      count++;
      boom = true;
      break;
    }
  }

  // 만약 별 탈없이 끝났을때 예외처리
  if(!boom) {
    count = 0;
    whatTimes = 0;
  }

  return [count, whatTimes];
}
profile
한걸음씩

0개의 댓글