GitHubSeob
C++ / 프로그래머스 / 영어 끝말잇기 본문
문제
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 };
}
'Programmers > Level 2' 카테고리의 다른 글
C++ / 프로그래머스 / 구명보트 (0) | 2023.07.04 |
---|---|
C++ / 프로그래머스 / 점프와 순간 이동 (0) | 2023.07.04 |
C++ / 프로그래머스 / 피보나치 수 (0) | 2023.06.29 |
C++ / 프로그래머스 / 다음 큰 숫자 (0) | 2023.06.29 |
C++ / 프로그래머스 / 최솟값 만들기 (0) | 2023.06.26 |