Algorithm

[프로그래머스] 오픈채팅방

robinjoon98 2021. 8. 30. 16:22

2019년 카카오 블라인드채용에서 출제된 문제이다. 

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

 

코딩테스트 연습 - 오픈채팅방

오픈채팅방 카카오톡 오픈채팅방에서는 친구가 아닌 사람들과 대화를 할 수 있는데, 본래 닉네임이 아닌 가상의 닉네임을 사용하여 채팅방에 들어갈 수 있다. 신입사원인 김크루는 카카오톡 오

programmers.co.kr

각 사용자들의 고유아이디와 변경가능한 닉네임을 매칭시키는 것이 이 문제의 핵심이다. 파이썬의 딕셔너리나, 자바의 Map 을 사용해 고유아이디 - 닉네임 쌍을 저장하면 된다.

주의할 점은, 문자열을 사용해서 답을 저장후 split 하여 배열로 만드는 것은 하면 안된다. 이렇게되면, 유저의 아이디가 다른 유저의 닉네임인 경우 문제가 발생하고, replace 하는 과정에서 많은 시간이 소요되기 때문이다. 아래는 내가 제출한 코드다.

def solution(record):
    dic = dict()
    commandlist = []
    answer = []
    for command in record:
        commands = command.split()
        if commands[0] == "Enter":
            uid = commands[1]
            nickname = commands[2]
            dic[uid] = nickname
            commandlist.append(["Enter", uid])
        elif commands[0] == "Leave":
            uid = commands[1]
            commandlist.append(["Leave", uid])
        else:
            uid = commands[1]
            nickname = commands[2]
            dic[uid] = nickname
    for command in commandlist:
        if command[0]=="Enter":
            answer.append(dic.get(command[1])+"님이 들어왔습니다.")
        else:
            answer.append(dic.get(command[1]) + "님이 나갔습니다.")
    return answer