오늘은 여기까지

[프로그래머스] 오픈채팅방 (Lv.2) - 자바 Java 본문

Problem Solving

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

dev-99 2024. 7. 1. 12:36

 

HashMap 활용하기 좋은 문제 같다.

import java.util.*;

class Solution {
    public String[] solution(String[] record) {
        HashMap<String, String> map = new HashMap<>();
        List<String> history = new ArrayList<>();
        
        for(String r : record) {
            String[] split_record = r.split(" ");
            if(split_record[0].equals("Enter")) {
                map.put(split_record[1], split_record[2]);
            } else if(split_record[0].equals("Change")) {
                map.put(split_record[1], split_record[2]);
            }
        }
        
        for(String r : record) {
            String[] split_record = r.split(" ");
            if(split_record[0].equals("Enter")) {
                history.add(map.get(split_record[1]) + "님이 들어왔습니다.");
            } else if(split_record[0].equals("Leave")) {
                history.add(map.get(split_record[1]) + "님이 나갔습니다.");
            } else {
                continue;
            }
        }
        String[] answer = history.stream().toArray(String[]::new);
        return answer;
    }
}

 

위와 아래는 같은 풀이인데 history 리스트에 아이디와 메세지를 동시에 저장할 수 있지 않을까 해서 찾아본 풀이다. 

결국 반환해야 되는 answer는 배열이라 후처리 해줘야 되는건 똑같다.

import java.util.*;

class Solution {
    public String[] solution(String[] record) {
        HashMap<String, String> map = new HashMap<>();
        List<String[]> history = new ArrayList<>();
        
        for(String r : record) {
            String[] split_record = r.split(" ");
            if(split_record[0].equals("Enter")) {
                map.put(split_record[1], split_record[2]);
                history.add(new String[] {split_record[1], "님이 들어왔습니다."});
            } else if(split_record[0].equals("Leave")) {
                history.add(new String[] {split_record[1], "님이 나갔습니다."});
            } else if(split_record[0].equals("Change")) {
                map.put(split_record[1], split_record[2]);
            }
        }
        String[] answer = new String[history.size()];
        for(int i=0; i<history.size(); i++) {
            // System.out.println(map.get(history.get(i)[0]) + history.get(i)[1]);
            answer[i] = map.get(history.get(i)[0]) + history.get(i)[1];
        }
        return answer;
    }
}