코딩테스트/기업코테
[2019 KAKAO BLIND] 오픈채팅방 (JAVA)
Jason of the Argos
2021. 9. 3. 21:14
https://programmers.co.kr/learn/courses/30/lessons/42888
코딩테스트 연습 - 오픈채팅방
오픈채팅방 카카오톡 오픈채팅방에서는 친구가 아닌 사람들과 대화를 할 수 있는데, 본래 닉네임이 아닌 가상의 닉네임을 사용하여 채팅방에 들어갈 수 있다. 신입사원인 김크루는 카카오톡 오
programmers.co.kr
풀이법:
1. 최종으로 변경된 닉네임으로 다 덮어 씌워지기 때문에 <id, 최신닉네임> 저장하는 HashMap 만들기
2. id + " " + Enter/Leave를 차례대로 리스트에 저장한다
3. 2번 리스트를 순회 하면서 id의 최종닉네임을 1번 HashMap에서 가져온다.
Comment:
1. 시간 복잡도는 O(2n).
코드:
import java.util.*;
class Solution {
public String[] solution(String[] record) {
HashMap <String, String> idMap = new HashMap();
ArrayList<String> logList = new ArrayList();
for(int i = 0 ; i < record.length; i++) {
String log = record[i];
String[] pLog = log.split(" ");
String cmd = pLog[0];
String id = pLog[1];
String nickname = "";
if(cmd.contentEquals("Change")) {
nickname = pLog[2];
idMap.put(id, nickname);
}else {
int code = -1;
if(cmd.contentEquals("Enter")) {
nickname = pLog[2];
code = 1;
idMap.put(id, nickname);
}else
code = 2;
String str = id + " " + code;
logList.add(str);
}
}
int finLen = logList.size();
String[] answer = new String[logList.size()];
for(int i = 0 ; i < finLen; i++) {
String[] pLog = logList.get(i).split(" ");
String id = pLog[0];
int code = Integer.parseInt(pLog[1]);
String finNick = idMap.get(id);
String postFix = "";
if(code == 1)
postFix = "님이 들어왔습니다.";
else
postFix = "님이 나갔습니다.";
String log = finNick + postFix;
//System.out.println(log);
answer[i] = log;
}
return answer;
}
}