접근
record
를 공백을 기준으로 split
한다
- 처음
Enter
하는 id
와 nickName
은 Map
에 저장하고, 동일한 id 인데 NickName이 다를 경우, 기존에 저장된 id 에 해당하는 nickname을 변경시켜준다.
Change
의 경우 역시 기존에 저장된 id에 해당하는 nickname을 변경시켜준다.
- change 의 수만큼
count
를 하고, record length - count 로 answer
배열 크기를 정해준다.
- record를 다시 한 번 공백을 기준으로 split 한 후 최신화되어 있는 Map 을 기준으로 answer를 return 한다.
나의 코드
import java.util.*;
public class Solution1 {
public String[] solution1(String [] record){
Map<String, String> map = new HashMap<>();
int cnt = 0;
for(String s : record){
String [] temp = s.split(" ");
if(temp[0].charAt(0)=='L') continue;
else if(temp[0].charAt(0)=='E'){
if(map.get(temp[1])!=null){
map.replace(temp[1],temp[2]);
}else
map.put(temp[1], temp[2]); // id, NickName
}else{
map.replace(temp[1],temp[2]);
cnt++;
}
}
String [] answer = new String[record.length - cnt];
for(int i=0 ; i < answer.length ; i++){
String [] temp = record[i].split(" ");
if(temp[0].charAt(0)=='E'){
answer[i] = map.get(temp[1])+"님이 들어왔습니다.";
}else if(temp[0].charAt(0)=='L'){
answer[i] = map.get(temp[1])+"님이 나갔습니다.";
}else
continue;
}
return answer;
}
public static void main(String[] args) {
Solution1 solution1 = new Solution1();
String [] records = {"Enter 1 a", "Enter 2 b","Enter 3 c","Leave 1", "Enter 1 d"};
String [] arr = solution1.solution1(records);
for(String s : arr)
System.out.println(s);
}
}