๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algortihm/Java][ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์˜คํ”ˆ์ฑ„ํŒ…๋ฐฉ

๋ฐ˜์‘ํ˜•

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์˜คํ”ˆ์ฑ„ํŒ…๋ฐฉ

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

๋ฌธ์ œ ์ ‘๊ทผ

HashMap์„ ์ด์šฉํ•ด์„œ ์œ ์ €์•„์ด๋””์™€ ๋‹‰๋„ค์ž„์„ ์ €์žฅํ•˜๊ณ 
list์— ์œ ์ € ์•„์ด๋””์™€ Enter or Leave๋ฅผ ์ €์žฅํ•œ ํ›„์— ๋ฉ”์„ธ์ง€๋ฅผ ์ถœ๋ ฅํ•  ๋•Œ ์œ ์ € ์•„์ด๋””์™€ ๋‹‰๋„ค์ž„์„ ๋งค์นญํ•ด์„œ ๋ฉ”์„ธ์ง€๋ฅผ ์ƒ์„ฑํ•˜์˜€๋‹ค.

Code

import java.util.HashMap;
import java.util.ArrayList;
class Solution {
    public String[] solution(String[] records) {
        String[] answer;
        HashMap<String, String> users = new HashMap<>();
        ArrayList<String> messages = new ArrayList<>();
        for(String record: records){
        //record ์ž…๋ ฅ
            String[] token = record.split(" ");
            String command = token[0];
            String uid = token[1];
            if(command.equals("Enter")){
                String nickname = token[2];
                users.put(uid,nickname);
                messages.add(uid + " Enter");
            } else if(command.equals("Change")){
                String nickname = token[2];
                users.put(uid,nickname);
            }
            else if(command.equals("Leave")){
                messages.add(uid + " Leave");
            }
        }
        answer = new String[messages.size()];
        // ๋ฉ”์„ธ์ง€ ์ถœ๋ ฅ
        for(int i = 0; i<messages.size(); i++){
            String[] message = messages.get(i).split(" ");
            String username = users.get(message[0]);
            if(message[1].equals("Enter")){
                answer[i] = username + "๋‹˜์ด ๋“ค์–ด์™”์Šต๋‹ˆ๋‹ค.";
            } else {
                answer[i] = username + "๋‹˜์ด ๋‚˜๊ฐ”์Šต๋‹ˆ๋‹ค.";
            }
        }
        return answer;
    }
}
๋ฐ˜์‘ํ˜•