https://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]
programmers.co.kr
문제설명
1부터 n까지 번호가 붙어있는 n명의 사람이 영어 끝말잇기를 하고 있습니다. 영어 끝말잇기는 다음과 같은 규칙으로 진행됩니다.
그냥 끝말잇기임.
사람의 수 n과 사람들이 순서대로 말한 단어 words 가 매개변수로 주어질 때, 가장 먼저 탈락하는 사람의 번호와 그 사람이 자신의 몇 번째 차례에 탈락하는지를 구해서 return 하도록 solution 함수를 완성해주세요.
문제풀이
1. 맵 형식으로 구현
2. 처음부터 틀린 경우는 없으므로 tank부터 맵에 넣고 시작
3. 맵에 단어가 이미 있거나 뒷 단어의 맨앞 글자와 현재단어의 맨뒷 단어 비교
4. 리턴 방식 :
map 자료구조 사용
ex) ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"]
key | value |
tank | 1 |
kick | 1 |
know | 1 |
wheel | 1 |
land | 1 |
dream | 1 |
mother | 1 |
robot | 1 |
tank | 2 |
return 방식
1. 사람 구하기 : (i%n)+1
2. 순서 구하기 : (i/n)+1
소스코드
#include <string>
#include <vector>
#include <map>
using namespace std;
vector<int> solution(int n, vector<string> words) {
map<string, int> word; //map형식으로 구현
word[words[0]]++;
for(int i=1; i<words.size(); i++){
//이미 단어가 있거나, 앞 뒤 단어 비교 틀린 것 찾기
if(word[words[i]] || words[i].front() != words[i-1].back())
return {(i%n)+1,(i/n)+1};
word[words[i]]++;
}
return {0, 0};
}
'Algorithm' 카테고리의 다른 글
[프로그래머스] n^2 배열 자르기 c++ (0) | 2021.12.22 |
---|---|
[프로그래머스] 1차 캐시 c++ (0) | 2021.12.22 |
[백준] 2580번 스도쿠 c++ (0) | 2020.11.09 |
[백준] 2110 공유기 설치 (이분탐색) C++ (0) | 2020.10.06 |
[백준 14888] 연산자 끼워넣기(C++, Java) (0) | 2020.09.09 |