[자바코딩] 카카오 오픈채팅방

gnoesnooj·2021년 12월 13일
0

접근

  1. record 를 공백을 기준으로 split 한다
  2. 처음 Enter 하는 idnickNameMap에 저장하고, 동일한 id 인데 NickName이 다를 경우, 기존에 저장된 id 에 해당하는 nickname을 변경시켜준다.
  3. Change 의 경우 역시 기존에 저장된 id에 해당하는 nickname을 변경시켜준다.
  4. change 의 수만큼 count를 하고, record length - count 로 answer 배열 크기를 정해준다.
  5. record를 다시 한 번 공백을 기준으로 split 한 후 최신화되어 있는 Map 을 기준으로 answer를 return 한다.

나의 코드

import java.util.*;

public class Solution1 {
    public String[] solution1(String [] record){
        Map<String, String> map = new HashMap<>();
        int cnt = 0;

        for(String s : record){
            String [] temp = s.split(" ");

            if(temp[0].charAt(0)=='L') continue;
            else if(temp[0].charAt(0)=='E'){

                if(map.get(temp[1])!=null){
                    map.replace(temp[1],temp[2]);
                }else
                    map.put(temp[1], temp[2]); // id, NickName

            }else{
                map.replace(temp[1],temp[2]);
                cnt++;
            }
        }

        String [] answer = new String[record.length - cnt];

        for(int i=0 ; i < answer.length ; i++){
            String [] temp = record[i].split(" ");
            if(temp[0].charAt(0)=='E'){
                answer[i] = map.get(temp[1])+"님이 들어왔습니다.";
            }else if(temp[0].charAt(0)=='L'){
                answer[i] = map.get(temp[1])+"님이 나갔습니다.";
            }else
                continue;
        }

        return answer;
    }

    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
        String [] records = {"Enter 1 a", "Enter 2 b","Enter 3 c","Leave 1", "Enter 1 d"};
        String [] arr = solution1.solution1(records);
        for(String s : arr)
            System.out.println(s);
    }
}
profile
누구나 믿을 수 있는 개발자가 되자 !

0개의 댓글