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

nnm·2020년 4월 16일
0

프로그래머스 오픈채팅방

문제풀이

이런 문제가 너무 좋다. 구조를 생각하고 구현하면 생각한대로 척척되는... 그렇다고 내 코드가 완벽한건 아니지만 그래도 뭔가 체계적으로 뭔가 된다는 느낌이 들 때 코딩이 정말 즐겁다.

  • 닉네임이 바뀌면 이전에 기록된 로그의 닉네임도 바꿔야한다.
  • 그렇다면 처음부터 변하지않는 유저ID로 로그를 기록하고 출력할 때만 유저ID를 최신화된 닉네임으로 바꿔주면 되겠다.
  • 닉네임은 HashMap으로 기록하고 ArrayList에 유저ID기반의 로그를 기록한다. 출력할때는 ArrayList를 String 배열에 담으면서 유저ID를 닉네임으로 바꾼다.

구현코드

import java.util.*;

class Solution {
    public String[] solution(String[] record) {
        ArrayList<String> chatLog = new ArrayList<>();
        HashMap<String, String> nickMap = new HashMap<>();
        
        for(String log : record){
            StringTokenizer st = new StringTokenizer(log);
            String command = st.nextToken();
            String userId = st.nextToken();
            String nickname = "";
            
            if(!command.equals("Leave")){
                nickname = st.nextToken();
            }
            
            switch(command){
                case "Enter":
                    nickMap.put(userId, nickname);
                    chatLog.add(userId + "님이 들어왔습니다.");
                    break;
                case "Leave":
                    chatLog.add(userId + "님이 나갔습니다.");
                    break;
                case "Change":
                    nickMap.put(userId, nickname);
                    break;
            }
        }
        
        String[] answer = new String[chatLog.size()];
        int logIdx = 0;
        
        for(String str : chatLog){
            int endOfId = str.indexOf("님");
            String userId = str.substring(0, endOfId);
            
            answer[logIdx++] = str.replace(userId, nickMap.get(userId));
        }
        
        return answer;
    }
}
profile
그냥 개발자

1개의 댓글

comment-user-thumbnail
2023년 6월 7일

import java.util.*;
class Solution {
public String[] solution(String[] record) {
//====================================
StringBuilder sb = new StringBuilder();
HashMap<String,String> user = new HashMap<>(); //아이디명, 닉네임
//====================================
for(int i=0;i<record.length;i++){
String[] word = record[i].split(" ");
if(word[0].equals("Enter") || word[0].equals("Change")){
user.put(word[1],word[2]);
}
}

    for(int i=0;i<record.length;i++){
        String[] word = record[i].split(" ");
        if(word[0].equals("Enter")){
            sb.append(user.get(word[1])+"님이 들어왔습니다.");
            sb.append("\n");
        }else if(word[0].equals("Leave")){
            sb.append(user.get(word[1])+"님이 나갔습니다.");
            sb.append("\n");
        }
    }
    
    return sb.toString().split("\n");
}

}
제 코드는 어떤가유

답글 달기