백준 등 알고리즘

[C#] 프로그래머스 영어 끝말잇기

박도치 2024. 11. 17. 18:40

https://school.programmers.co.kr/learn/courses/30/lessons/12981

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

사람수 n만큼 영어 끝말잇기를 하는 문제이다. 사람수 n과 단어 배열 words를 받아서 단어를 뱉고, 이를 HashSet에 add하여 중복된 단어를 넣지 않게하고 이미 사용됐는지 체크를 하면 되는 문제이다.

 

player와 round는 player의 경우 i번 반복할 경우 i % n + 1 로 나머지 개수로 사람의 번호를 체크하고, round는 나눗셈으로 하면 된다.

 

using System;
using System.Collections.Generic;

class Solution
{
     public int[] solution(int n, string[] words)
     {
          HashSet<string> usedWords = new HashSet<string>();
          int turn = 0;

          for (int i = 0; i < words.Length; i++)
          {
              // 현재 말한 사람의 번호와 차례 계산
              int player = i % n + 1;
              int round = i / n + 1;

              // 현재 단어
              string currentWord = words[i];

              // 이전 단어의 마지막 문자와 현재 단어의 첫 문자 비교
              if (i > 0 && words[i - 1][words[i - 1].Length - 1] != currentWord[0])
              {
                  return new int[] { player, round };
              }

              // 이미 사용된 단어인지 확인
              if (usedWords.Contains(currentWord))
              {
                  return new int[] { player, round };
              }

              // 단어를 사용된 단어 집합에 추가
              usedWords.Add(currentWord);
          }

          // 탈락자가 없는 경우
          return new int[] { 0, 0 };
     }   
}