GitHubSeob

C++ / 프로그래머스 / 영어 끝말잇기 본문

Programmers/Level 2

C++ / 프로그래머스 / 영어 끝말잇기

GitHubSeob 2023. 6. 29.

문제

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

 

코딩테스트 연습 - 영어 끝말잇기

3 ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"] [3,3] 5 ["hello", "observe", "effect", "take", "either", "recognize", "encourage", "ensure", "establish", "hang", "gather", "refer", "reference", "estimate", "executive"] [0,0]

school.programmers.co.kr

문제풀이

끝말잇기를 지는 경우는 세 가지이다.

1. 이미 말한 단어를 말하는 경우

2. 앞 단어의 끝문자와 말한 첫 문자가 다른 경우

3. 한 글자 단어를 말하는 경우

 

map을 이용해 이미 말한 단어들을 저장한다.

prev는 이전 단어의 끝 문자를 저장하는 변수이다.

반복문을 돌려 세 조건을 만족하면 졌으므로 사람의 번호, 몇 번째 차례인지를 return 하면 된다.

 

코드

#include <string>
#include <vector>
#include <map>
using namespace std;

vector<int> solution(int n, vector<string> words) {
    char prev(words[0][0]);
    map<string, int>log;

    for (int idx = 0; idx < words.size(); ++idx) {
        if (log[words[idx]] == 1 || prev != words[idx][0] || words[idx].size() == 1) {
            return { idx % n + 1 , idx / n + 1 };
        }
        log[words[idx]]++;
        prev = words[idx].back();
    }
    return { 0,0 };
}