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
def solution(n, words):
access_list = set()
before = words[0][0]
cnt,fin_idx = 0,0
isFin = False
for idx, word in enumerate(words):
if idx % n == 0:
cnt += 1
if before[-1] == word[0] and word not in access_list:
access_list.add(word)
before = word
else:
isFin = True
fin_idx = idx
break
if isFin:
return [fin_idx%n+1,cnt]
else:
return [0,0]
풀이
1. access_list : 통과된 단어를 관리하는 집합
2. before : 이전 단어를 기억 (초기값은 첫 단어의 첫 번째 요소)
3. 끝말잇기 시작 (words 리스트 for문)
- n으로 나눈 나머지가 0이 되면 cnt 증가 (cnt 번째 차례)
- 이전 단어의 마지막 요소와 현재 단어의 첫 번째 요소가 같고, 중복 단어가 아니라면 통과
- 아니라면 게임 끝, fin_idx 기억
4. isFin : 도중에 게임이 끝났는지 기억
- isFin 이면, [해당 사람, 차례] 리턴
- 아니면, [0, 0] 리턴
'Algorithm > 프로그래머스' 카테고리의 다른 글
[프로그래머스] Lv2 - 모음사전 (파이썬) (0) | 2022.05.03 |
---|---|
[프로그래머스] Lv2 - 전력망을 둘로 나누기 (파이썬) (0) | 2022.05.03 |
[프로그래머스] Lv2 - 삼각 달팽이 (파이썬) (0) | 2022.04.11 |
[프로그래머스] Lv2 - 2개 이하로 다른 비트 (파이썬) (0) | 2022.04.06 |
[프로그래머스] Lv2 - 피로도 (파이썬) (0) | 2022.04.06 |