알고리즘/프로그래머스
[프로그래머스] 오픈채팅방
송민준
2022. 4. 28. 20:18
https://programmers.co.kr/learn/courses/30/lessons/42888?language=java
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
class Solution {
public String[] solution(String[] record) {
// 아이디와 닉네임을 보관하는 user
Map<String, String> user = new HashMap<String, String>();
// 메시지를 보관하는 result
List<Result> result = new ArrayList<Result>();
// 메시지에는 아이디 + boolean(true : 들어왔다 , false : 나갔다)
for(String re : record) {
String[] reArray = re.split(" ");
String command = reArray[0];
String uid = reArray[1];
switch(command) {
case "Enter":
user.put(uid, reArray[2]);
result.add(new Result(uid, true));
break;
case "Leave":
result.add(new Result(uid, false));
break;
case "Change":
user.put(uid, reArray[2]);
break;
default:
break;
}
}
String[] answer = new String[result.size()];
for(int i = 0; i < result.size(); i++) {
Result temp = result.get(i);
answer[i] = temp.getMsg(user);
}
return answer;
}
class Result {
private String id;
private Boolean isEnter;
public String getMsg(Map<String, String> user) {
String convertMsg = isEnter ? "님이 들어왔습니다." : "님이 나갔습니다.";
return user.get(id) + convertMsg;
}
public Result(String id, Boolean isEnter) {
this.id = id;
this.isEnter = isEnter;
}
}
}
1년 전 풀었던 코드
효율성을 통과 못했던 것 같다...
코드 수준도 ...ㅎㅎ
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
class Solution {
public String[] solution(String[] record) {
HashMap<String, String> user = new HashMap<String, String>();
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> matchId = new ArrayList<String>();
for(String re : record) {
String[] reArray = re.split(" ");
if(reArray.length != 2) {
user.put(reArray[1], reArray[2]);
}
switch(reArray[0]) {
case "Enter" :
if(!user.containsKey(reArray[1])) { //처음 들어온 회원
result.add(user.get(reArray[1]) + "님이 들어왔습니다.");
matchId.add(reArray[1]);
} else { // 처음 들어온 회원이 아님
for(int i =0; i < matchId.size(); i++) { //List 길이만큼
if(reArray[1].equals(matchId.get(i))) { // 들어온 아이디가 List의 아이디가 같다면
StringBuilder active = new StringBuilder("");
active.append(result.get(i).substring(result.get(i).indexOf("님"))); //님이 ~ 했습니다
result.set(i, reArray[2]+active.toString()); // 닉넴 + 행동으로 바꿔줌
}
}
result.add(user.get(reArray[1]) + "님이 들어왔습니다.");
matchId.add(reArray[1]);
}
break;
case "Leave" :
result.add(user.get(reArray[1]) + "님이 나갔습니다.");
matchId.add(reArray[1]);
break;
default :
for(int i =0; i < matchId.size(); i++) { //List 길이만큼
if(reArray[1].equals(matchId.get(i))) {
StringBuilder active = new StringBuilder("");
active.append(result.get(i).substring(result.get(i).indexOf("님"))); //님이 ~ 했습니다
result.set(i, reArray[2]+active.toString()); // 닉넴 + 행동으로 바꿔줌
}
}
break;
}
}
String[] answer = new String[result.size()];
answer = result.toArray(answer);
return answer;
}
}