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

journey📸·2021년 9월 17일
0

코딩테스트 - JAVA

목록 보기
2/7
post-thumbnail

💻문제 설명


🔎 나의 해결 방식

HashMap<String, String> user = new HashMap<>();
for(String str : record){
            String[] arr = str.split(" ");
            String cmd = arr[0];
            String uid = arr[1];


            if(arr.length>2){
                user.put(uid, arr[2]);
            }
            if(cmd.equals("Enter")||cmd.equals("Leave")){
                commands.add(cmd);
                ids.add(uid);
            }
        }

📍
해시맵을 이용하여 유저의 아이디와 닉네임을 저장한다. Enter와 Change인 경우 put을 하여 닉네임 변경을 적용한다.

📍
유저가 들어오거나 나가는 경우의 메세지를 순서대로 보관하기위하여 출입메세지 리스트와 유저 아이디 리스트를 생성하여 순서대로 삽입한다.

💡 코드

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

class Soultion{

    public String[] solution(String[] record) {

        HashMap<String, String> user = new HashMap<>();
        List<String> commands = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        for(String str : record){
            String[] arr = str.split(" ");
            String cmd = arr[0];
            String uid = arr[1];


            if(arr.length>2){
                user.put(uid, arr[2]);
            }
            if(cmd.equals("Enter")||cmd.equals("Leave")){
                commands.add(cmd);
                ids.add(uid);
            }

        }
        String[] answer = new String[commands.size()];
        for(int i = 0; i<commands.size(); i++){
            StringBuilder str = new StringBuilder();
            String name = user.get(ids.get(i));
            str.append(name);
            if(commands.get(i).equals("Enter")){
                str.append("님이 들어왔습니다.");
            }else{
                str.append("님이 나갔습니다.");
            }
            answer[i] = str.toString();
        }

        return answer;
    }


}
profile
https://iwntberich.tistory.com/

0개의 댓글