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

래우기·2021년 11월 14일
1

프로그래머스 LV.2

목록 보기
3/6
post-thumbnail

1. 문제 링크

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

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(변경 대상 문자열, 변경할 문자열)
profile
지금 당장 시작해

1개의 댓글

comment-user-thumbnail
2021년 11월 14일

대단해요!

답글 달기