[코딩테스트] 오픈채팅방

Doccimann·2022년 5월 7일
0

코테 9주차

목록 보기
1/4
post-thumbnail

출처: https://programmers.co.kr/learn/courses/30/lessons/42888


우선 문제부터 분석해보겠습니다.

문제가 요구하는 정답부터 분석해봅시다. 문제에서 요구하는 답은 다음과 같습니다.

사용자가 들어오고, 나가고, 닉네임을 변경하기를 반복하는데 마지막에 방의 개설자가 확인하게되는 히스토리를 반환하여라

일단 제 아이디어는 이렇습니다.

  • record를 먼저 읽어서 Enter, Change의 경우 닉네임의 변동이 발생하기 때문에 change_history를 만들어둔다
  • change_history를 완성한 다음에 다시 record를 읽어서 change_history를 참조하여 answer에다가 문장을 append 시킨다

이것만 알면 문제 해결은 어렵지 않습니다.


코드를 확인해봅시다!

def solution(record):
    answer = []
    
    change_history = {}
    
    for history in record:
        instruction = list(history.split())
        
        # change, Enter 명령인 경우
        if instruction[0] == 'Change' or instruction[0] == 'Enter':
            change_history[instruction[1]] = instruction[2] # 변경된 닉네임 저장
    
    # 닉네임을 변경한 user_id의 목록
    uid_list = change_history.keys()
    
    # answer 갱신
    for history in record:
        instruction = list(history.split())
        
        # Enter or Leave인 경우
        if instruction[0] == 'Enter' or instruction[0] == 'Leave':
            nickname = change_history[instruction[1]]
            
            sentence = nickname + '님이 들어왔습니다.' if instruction[0] == 'Enter' else nickname + '님이 나갔습니다.'
            answer.append(sentence)
    
    return answer

설명은 생략하겠습니다. 그저 위의 설명을 코드로 옮겼을 뿐이니까요 🤗

profile
Hi There 🤗! I'm college student majoring Mathematics, and double majoring CSE. I'm just enjoying studying about good architectures of back-end system(applications) and how to operate the servers efficiently! 🔥

0개의 댓글