티스토리 뷰

문제 링크

 

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

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

programmers.co.kr

 

풀이

풀이는 간단하다.

map을 이용하였고 map의 "[ ]" operator 연산자로 insert와 update를 동시에 해주는 이점을 이용하였다.

(= key값이 중복이 안되는 점을 이용)

 

1) 선 처리 과정에서는 첫 글자만 보고 'C', 'E', 'L'로만으로 switch-case로 나눠서 진행

 

1.1)Change는 닉네임을 갱신

1.2)Enter는 answer 컨테이너에 id + "님이 들어왔습니다."를 넣어주는 동시에, 닉네임을 갱신

1.3)Leave는 answer 컨테이너에 id + "님이 나갔습니다."를 넣어준다.

 

 

2) 후 처리로 id에 해당되는 닉네임을 replace 해준다.

 

더보기
#include <string>
#include <vector>
#include <iostream>
#include <map>

using namespace std;

vector<string> solution(vector<string> record) {
    vector<string> answer;
    map<string, string> id_name;
    // recode에서 uid를 다 뽑아오기(uid는 공통이므로)
    for(string s : record)
    {
        int count;
        string id;
        string name;
        switch(s[0])
        {
            case 'E':
                count = s.find(" ", 6) - 6;     // "Enter " 다음부터 " "찾아서 글자 길이 추출
                id = s.substr(6, count);         // id
                name = s.substr(6+count+1);          // nickname
                id_name[id] = name;         // insert to map
                answer.push_back(id+"님이 들어왔습니다.");
                break;
            case 'L':
                id = s.substr(6);
                answer.push_back(id+"님이 나갔습니다.");
                break;
            case 'C':
                count = s.find(" ", 7) - 7;     // "Enter " 다음부터 " "찾아서 글자 길이 추출
                id = s.substr(7, count);         // id
                name = s.substr(7+count+1);          // nickname
                id_name[id] = name;         // change value of the key
                break;
        }
    }
    
    // 후 처리
    for(string& s : answer)         // 참조하여 id를 nickname으로 바꿔줌
    {
        int count = s.find("님");
        string id = s.substr(0, count);
        s.replace(0, count, id_name.find(id)->second);
    }
    
    return answer;
}
728x90
반응형
댓글
05-01 21:42
링크