본문 바로가기
알고리즘/프로그래머스 LV.2

프로그래머스 LV.2 오픈채팅방

by 호롤롤로루야 2022. 1. 12.

프로그래머스 LV.2 오픈채팅방

1. 문제 링크

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

 

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

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

programmers.co.kr

2. 문제 해결에 대한 아이디어

  1. HashMap<String, String> hm 으로 key : uid / value : name을 저장한다.
  2. Enter와 Leave에 한해서 answer에 "{uid} 들어왔습니다./나갔습니다." 로 저장한다.
  3. 기록이 끝난 뒤, uid 를 "name님이"로 바꿔준다.
  4. Change일 때, 이미 존재하는 key:value 이면 새로운 value가 HashMap에 overwrite 된다.

 

3. 코드

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

public class Solution {

    static HashMap<String, String> hm = new HashMap<>();

    public ArrayList<String> solution(String[] record) {
        ArrayList<String> answer = new ArrayList<>();
        for (int i = 0; i < record.length; i++) {
            // 초기화
            String[] line = record[i].split(" ");
            String action = line[0];
            String uid = line[1];
            String name = "";

            // Enter, Change 인 경우에만 name 이 있다.
            if (line.length == 3) {
                name = line[2];
            }

            // name 이 빈 값이 아니면 uid 와 닉네임을 매핑해준다.
            // 이미 존재하는 key:value 구성인 경우, 새로운 value 가 overwrite 된다.
            if (!name.isEmpty())
                hm.put(uid, name);

            //각 동작별 메시지를 생성
            StringBuilder sb = new StringBuilder();
            sb.append(uid);
            if (action.equals("Enter")) {
                sb.append(" 들어왔습니다.");
            } else if (action.equals("Leave")) {
                sb.append(" 나갔습니다.");
            }

            // 닉네임 변경 기록은 출력되지 않는다.
            if (!action.equals("Change"))
                // "uid 들어왔습니다." or "uid 나갔습니다." 로 저장
                answer.add(sb.toString());
        }

        // uid 를 닉네임으로 바꿔준다.
        for (int i = 0; i < answer.size(); i++) {
            String uid = answer.get(i).split(" ")[0];
            String change = answer.get(i).replace(uid, hm.get(uid) + "님이");
            answer.set(i, change);
        }

        return answer;
    }
}

4. 채점 결과

5. 느낀 점

  1. HashMap의 put(key, value)를 사용할 때, 이미 있는 key인 경우, 새로운 value가 overwrite 된다.
  2. string.replace(변경 대상 문자열, 변경할 문자열)

 

 

댓글