알고리즘 공부/프로그래머스

(Java)프로그래머스 코딩테스트 연습 - 2019 KAKAO BLIND RECRUITMENT - 오픈채팅방

HRuler 2020. 12. 1. 22:16

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/42888?language=java

 

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

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

programmers.co.kr

2. 나의 풀이

import java.util.*;

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

3. 다른 사람 풀이

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Solution {
    public String[] solution(String[] record) {
        HashMap<String, String> codeMap = new HashMap<String, String>();
        codeMap.put("enter","들어왔습니다.");
        codeMap.put("leave","나갔습니다.");

        HashMap<String, String> uidMap = new HashMap<String, String>();
        List<String> list = new ArrayList<String>();
        for(String str:record){
            String[] split = str.split("\\s+");
            String code = split[0];
            String uid = split[1];
            if(split.length > 2) {
                String name = split[2];
                uidMap.put(uid, name);
            }
            if(!"Change".equalsIgnoreCase(code)){
                list.add(code +" "+uid);
            }

        }
        String[] answer = new String[list.size()];
        for(int i=0;i<answer.length;i++){
            String[] split = list.get(i).split("\\s+");
            String name = uidMap.get(split[1]);
            answer[i] = name+"님이 "+ codeMap.get(split[0].toLowerCase());
        }

        return answer;
    }
}