본문 바로가기
Algorithm/Programmers

[프로그래머스(programmers)] (2019 KAKAO BLIND RECRUITMENT) 오픈채팅방

by 광진구뚝배기 2021. 5. 27.

알고리즘 문제 풀이 / 프로그래머스 (programmers)  -  오픈채팅방

 

 

문제 링크

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

 

 

문제 풀이

 

split 을 사용하여 E / L / C , 유저아이디, 유저닉네임 이렇게 세개로 나눴다.

hashmap 을 사용하여 유저아이디에 따른 마지막 설정한 유저닉네임을 넣어줬다.

 

처음 풀었을 땐 리스트를 배열로 옮김과 동시에 마지막 변경된 유저 닉네임을 고쳐주기 위하여 replace를 사용하여 고쳐줬었다. 그런데 25번 부터 32번까지 시간초과가 났다. 

문장을 만들고 바뀐 닉네임을 다시 변경을 하는 로직이여서 오래걸린단 생각에 반대로 유저닉네임들부터 바꾸고 문장을 만들잔 생각을 했다. 그래서 replace를 사용하지않고, 유저닉네임들 먼저 변경시켜 준 후, 리스트에 넣고 toArray()를 사용하여 배열로 바꿔줬다.

 

 

첫 번째 풀이(시간초과)

public static String[] solution(String[] record) {
	HashMap<String, String> map = new HashMap<>();
	List<String> list = new LinkedList<>();

	for(int i = 0; i < record.length; i++) {
		String[] split = record[i].split(" ");

		if(split[0].equals("Enter")) {
			map.put(split[1], split[2]);
			list.add(split[1]+"님이 들어왔습니다.");
		}else if(split[0].equals("Leave")) {
			list.add(split[1] + "님이 나갔습니다.");
		}else {
			map.put(split[1], split[2]);
		}

	}

	String[] answer = new String[list.size()];
	for(int i = 0; i < list.size(); i++) {
		String[] split = list.get(i).split("님");
		answer[i] = list.get(i).replaceAll(split[0], map.get(split[0]));

	}
}

 

두번째 풀이(성공)

public static String[] solution(String[] record) {

	HashMap<String, String> map = new HashMap<>();
	List<String> list = new LinkedList<>();

	for(int i = 0; i < record.length; i++) {
		String[] split = record[i].split(" ");
		if(!split[0].equals("Leave")) {
			map.put(split[1], split[2]);
		}
	}

		
	for(int i = 0; i < record.length; i++) {
		String[] split = record[i].split(" ");
		if(split[0].equals("Enter")) {
			list.add(map.get(split[1]) + "님이 들어왔습니다.");
		}else if(split[0].equals("Leave")) {
			list.add(map.get(split[1]) + "님이 나갔습니다.");
		}
	}

	String answer[] = list.toArray(new String[list.size()]);
		
	return answer;
}

 

반응형

댓글