자바/코딩테스트

[프로그래머스] 오픈채팅방 - Java(자바)

대전집주인 2024. 4. 2. 17:25
728x90
SMALL

 

문제 이해

  • 오픈채팅방에 들어오거나 나갈때 문자열로 기록이 된다.
  • 오픈채팅방을 나갔다가 같은 아이디로 들어왔을때 닉네임이 변경되어있으면 기록된 문자열에 닉네임도 바뀌어야한다.
  • 채팅방을 나가지 않고 닉네임을 변경하였을 경우도 문자열의 닉네임이 바뀌어야한다.
  • 배열의 길이는 100,000 건으로 for문 내에 함수를 사용하거나 메모리 사용량이 적은걸로만 사용해야한다.
  • map을 생성하고 key = id , value = 닉네임 형태로 배열전체를 돌면서 설정한다.
  • map에 id로 할당된 닉네임이 최종 닉네임이다.
import java.util.*;
class Solution {
    public String[] solution(String[] record) {
        Map<String, String> map = new HashMap<>();
        List<String> result = new ArrayList();
        
        for(int i = 0; i<record.length; i++){
            String[] temp = record[i].split(" ");
            if(!"Leave".equals(temp[0])){
                map.put(temp[1], temp[2]);  
            }
        }
        
        for(int i = 0; i<record.length; i++){
            String[] temp = record[i].split(" ");
            if("Enter".equals(temp[0])){
                result.add(map.get(temp[1]) + "님이 들어왔습니다.");
            }else if("Leave".equals(temp[0])){
                result.add(map.get(temp[1]) + "님이 나갔습니다.");
            }
        }
        
        String[] answer = new String[result.size()];
        
        for(int i = 0; i<result.size(); i++)
            answer[i] = result.get(i);
        
        return answer;
    }
}
728x90
LIST