본문 바로가기
알고리즘/프로그래머스

[프로그래머스] 영어 끝말잇기(python)

by 김홍중 2021. 5. 14.

1. 문제

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

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

 

2. 설명

 

3. 접근

  • 중복된 답을 하는 경우는 해시를 이용해서 value값이 1인 경우 return합니다.
  • 끝말잇기가 틀린 경우는 for문으로 word 하나하나를 접근하면서 이전 word와 비교합니다.
  • 그 외의 경우는 정상적으로 끝말잇기가 끝난것으로 [0, 0]을 리턴합니다.

 

4. 코드

def solution(n, words):
    dictionary = dict.fromkeys(words, 0)
    
    i = 0    
    for word in words:
        is_incorrect = i > 0 and prev_word[length - 1] != word[0]
        is_redundant = dictionary[word] != 0
        
        if is_incorrect or is_redundant:
            return [(i % n) + 1 , int(i / n) + 1]
        if not is_redundant:
            dictionary[word] += 1
        i += 1
        prev_word = word
        length = len(prev_word)
    return [0,0]

댓글