최대 1 분 소요

Question

Q Q2 Q3


Solution

  • 중복되는 단어를 검사하고 저장할 unordererd_set을 선언한다.
  • 이전 단어의 마지막과 현재 단어의 첫 알파벳이 같은지 검사한다.
  • 현재 words의 인덱스를 n 사람 수 만큼 나눈 나머지의 + 1 즉, i % n + 1 이 n번째 사람이 말한 단어가 된다.
  • 중복된 단어나 틀린 단어를 말하면 즉시 answer에 push하고 return 시킨다.
  • 가장 처음 i = 0 인 경우는 비교할 단어가 없기 때문에 예외 시켜준다.

Cord

#include <string>
#include <vector>
#include <iostream>
#include <unordered_set>

using namespace std;

vector<int> solution(int n, vector<string> words)
{
    vector<int> answer;
    int people[11] = { 0 };
    unordered_set<string> data;
    
    for (int i = 0; i < words.size(); i++)
    {
        int order = i % n + 1;
        people[order]++;

         // 마지막과 첫 알파벳 변수
        int lastSize = 0;
        char lastAlpha = '0';
        char startAlpha = words[i][0];
        if (i > 0)
        {
            lastSize = words[i - 1].size() - 1;
            lastAlpha = words[i - 1][lastSize];
        }

        // 1. 중복된 키가 있는지 검사 (없으면 data에 해당 단어 저장)
        // 2. 시작 알파벳이 이전 단어의 마지막 알파벳과 같은지 검사 
        if (data.find(words[i]) == data.end() && (lastAlpha == startAlpha) || i == 0)
        {
            data.insert(words[i]);
        }
        else
        {
            answer.push_back(order);
            answer.push_back(people[order]);
            return answer;
        }
    }

    // 아무도 틀리지 않았을때
    answer.push_back(0);
    answer.push_back(0);
    return answer;
}

Result

Result