알고리즘 풀이/프로그래머스

[level2] 프로그래머스 - 오픈채팅방(JAVA)

데롱디롱 2021. 9. 2. 19:23
728x90

- 채팅방 의 다음과 같은 내용을 Queue에 저장한다.

어떤 [아이디][들어왔 / 나갔]는지

 

 

- 닉네임정보를 Map에 저장한다.
    ㄴ id별 닉네임을 저장하면, Change가 되었을때, 바뀐 닉네임으로 조회가 가능하다.

Key : 아이디
Value : 닉네임

 

 

- Queue에서 하나씩 꺼내면서
   해당 id에 해당하는 닉네임을 Map에서 조회하고 출력형식을 맞춰준다.

 

 

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

class Solution {
    public String[] solution(String[] record) {
        HashMap<String, String> nickName = new HashMap<String, String>(); // (아이디, 닉네임)
        Queue<String[]> chat = new LinkedList<String[]>();
        for (int i = 0; i < record.length; i++) {
            StringTokenizer st = new StringTokenizer(record[i]);
            String action = st.nextToken(); // 행동
            String id = st.nextToken(); // 아이디

            if (!action.equals("Leave"))
                nickName.put(id, st.nextToken());

            if (!action.equals("Change"))
                chat.offer(new String[] { action, id }); // 입퇴장여부, 아이디
        }

        int i = 0;
        String[] answer = new String[chat.size()];
        while (!chat.isEmpty()) {
            String[] s = chat.poll();

            if (s[0].equals("Enter"))
                answer[i++] = nickName.get(s[1]) + "님이 들어왔습니다.";
            else
                answer[i++] = nickName.get(s[1]) + "님이 나갔습니다.";
        }

        return answer;
    }
}

 

댓글수0