본문 바로가기

알고리즘/프로그래머스

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

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

 

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

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

programmers.co.kr

풀이 방법

import java.util.*;

public class Solution {
	public static String[] solution(String[] record) {
		String[] answer;
		StringTokenizer st;
		Map<String, String> user = new HashMap<String, String>(); // 유저아이디, 닉네임
		List<Pair> inout = new ArrayList<>();
		for (int i = 0; i < record.length; i++) {
			st = new StringTokenizer(record[i]);
			String act = st.nextToken(); // 유저의 행동
			String id = st.nextToken(); // 유저아이디
			if (act.equals("Enter")) {
				inout.add(new Pair(id, 1));
			} else if (act.equals("Leave")) {
				inout.add(new Pair(id, 2));
				continue;
			}
			String nickname = st.nextToken(); // 닉네임
			user.put(id, nickname);	// 키값(유저아이디)이 없다면 유저 등록, 있다면 닉네임 변경
		}

		int size = inout.size();
		answer = new String[size];
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < size; i++) {
			sb.append(user.get(inout.get(i).id)).append("님이 ");
			if (inout.get(i).inout == 1) { // 입장
				sb.append("들어왔습니다.");
			} else { // 퇴장
				sb.append("나갔습니다.");
			}

			answer[i] = sb.toString();
			sb.setLength(0);
		}
		return answer;
	}

}

class Pair {
	String id; // 유저 아이디
	int inout; // 입장:1, 퇴장:2

	public Pair(String id, int inout) {
		super();
		this.id = id;
		this.inout = inout;
	}
}