코딩테스트/프로그래머스
[프로그래머스] 오픈채팅방 (Lv.2)
34suuuuu
2025. 4. 5. 15:15
✴️ 문제
https://school.programmers.co.kr/learn/courses/30/lessons/42888
✴️ 문제 풀이
(유저 아이디, 닉네임)을 저장하는 map을 만들어서 최종적인 유저 아이디와 닉네임을 저장하도록 했다.
즉, `Enter`면 map에 추가, `Change`면 `replace`, `Leave`면 별도의 처리 없이 진행했다.
그 후 다시 `record`를 for문으로 탐색하며
`Enter`와 `Leave`에 대해서 map에서 유저의 아이디를 통해 닉네임을 가져와 메시지를 만들고 List에 추가해줬다.
마지막으로 반환 타입이 String[]이기 때문에 List를 타입에 맞게 변환해서 리턴해준다.
✴️ 전체 코드(Java)
import java.util.*;
class Solution {
public String[] solution(String[] record) {
String[] answer = {};
Map<String, String> names = new HashMap<>();
for(String input : record){
String[] cmd = input.split(" ");
if(cmd[0].equals("Change")){
// 기존의 이름 변경
names.replace(cmd[1], cmd[2]);
}else if(cmd[0].equals("Enter")){
// 없으면 추가
names.put(cmd[1], cmd[2]);
}
}
List<String> list = new ArrayList<>();
for(String input : record){
String[] cmd = input.split(" ");
if(cmd[0].equals("Enter")){
list.add(names.get(cmd[1])+"님이 들어왔습니다.");
}else if(cmd[0].equals("Leave")){
list.add(names.get(cmd[1])+"님이 나갔습니다.");
}
}
return list.stream().toArray(String[]::new);
}
}