순간을 기록으로

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

카테고리 없음

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

luminous13 2022. 2. 13. 14:59

문제

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

 

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

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

programmers.co.kr

풀이

첫 번째 반복문으로 이름을 map에 저장하고 업데이트를 하고, answer 배열의 길이를 구한다

두 번째 반복문으로 answer 배열 원소의 값을 구한다.

 

코드

package 프로그래머스.레벨2.오픈채팅방.첫풀이;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public String[] solution(String[] record) {
        String[] answer;
        Map<String, String> map = new HashMap<>();
        int count=0; // 결과 배열의 길이를 저장하기위해 선언

        for (int i=0; i< record.length; i++) {
            String[] temp = record[i].split(" ");
            String command = temp[0];   // 명령어
            String id = temp[1];        // 아이디
            String nickName = null;     // 닉네임

            if (command.equals("Enter")) {  // 입장
                nickName = temp[2];
                map.put(id, nickName); // 키:id 값:닉네임
                count++;
            }
            else if (command.equals("Leave")) {
                count++;
            }
            else {  // Change
                nickName = temp[2];
                map.put(id, nickName);
            }
        }
        answer = new String[count]; // "Enter"과 "Leave"가 언급됫 횟수만큼 배열을 선언

        count = 0;  // 0으로 다시 초기화

        for (int i=0; i< record.length; i++) {
            String[] temp = record[i].split(" ");
            String command = temp[0];
            String id = temp[1];
            
            if (command.equals("Enter")) {
                answer[count] = map.get(id) + "님이 들어왔습니다.";
                count++;
            }
            else if (command.equals("Leave")) {
                answer[count] = map.get(id) + "님이 나갔습니다.";
                count++;
            }
            else {
                continue;
            }
        }

        return answer;
    }

    @Test
    void test() {
        Assertions.assertArrayEquals(new String[]{"Prodo님이 들어왔습니다.",
                "Ryan님이 들어왔습니다.", "Prodo님이 나갔습니다.", "Prodo님이 들어왔습니다."}
        , solution(new String[]{"Enter uid1234 Muzi", "Enter uid4567 Prodo",
                        "Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"}));

    }
}
Comments