[프로그래머스/C++]Lv.2 - 영어 끝말잇기

YH J·2023년 6월 22일
0

프로그래머스

목록 보기
135/168

문제 링크

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

내 풀이

중복검사에 unordered_map을 사용하였다. 중복된 단어를 사용했거나 앞의 단어의 맨 뒤 글자가 지금 단어의 시작과 다르면 해당 인덱스를 기반으로 번호와 차례를 계산해서 리턴한다.
주의할것은 첫 단어는 미리 map에 추가하고 break를 쓰거나 바로 return을 한다.

내 코드

#include <string>
#include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;

vector<int> solution(int n, vector<string> words) {
    vector<int> answer{0,0};
    unordered_map<string,int> wordmap;
    wordmap[words[0]]++;
    
    for(int i = 1; i < words.size(); i++)
    {
        if(wordmap[words[i]] || (words[i - 1].back() != words[i].front()))
        {
            answer[0] = i % n + 1;
            answer[1] = i / n + 1;
            break;
        }
        else
            wordmap[words[i]]++;
    }

    return answer;
}

다른 사람의 풀이

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

using namespace std;
vector<int> solution(int n, vector<string> words) {
    unordered_set<string> said_words;                       //O(1)으로 말한 단어인지 체크할 수 있는 컨테이너
    for(int i=0; i<words.size(); ++i)
        if(!said_words.insert(words[i]).second ||           //이미 말한 단어이거나
           (i>0 && words[i-1].back() != words[i].front()))  //앞에서 말한 단어의 끝으로 시작하지 않을 때
            return {i%n+1,i/n+1};                           //탈락자번호와 탈락자가 몇번째로 말한 단어인지 반환
    return {0,0};                                           //끝까지 탈락자 발생 안한 경우
}

다른 사람의 풀이 해석

unordered_set을 사용하였고, 이미 말한 단어를 체크 할 때
저렇게 쓰는 이유는 unordered_set의 insert함수의 return value가 pair<iterator,bool> 이므로 second 즉 bool을 기반으로 체크했다.

profile
게임 개발자 지망생

0개의 댓글