[프로그래머스] 2019 KAKAO BLIND RECRUITMENT : 오픈채팅방 (C++)

김영한·2021년 9월 2일
0

알고리즘

목록 보기
69/74

문제 링크 : 오픈채팅방

[문제 접근]

적절한 자료구조를 사용하면 쉽게 풀 수 있는 문제이다.

id값에 따른 닉네임을 map 자료구조에 저장해놓고 변경시에 저장된 값을 변경해준다.
queue를 사용해 채팅 순서를 저장한다.
이 때, queue의 자료형은 구조체로 만들어서 queue 당 어떤 id값을 가지고 있는지 enter인지 leave인지 알 수 있게 설정해주었다.

그 후 queue를 탐색하면서 id값을 통해 map에서 닉네임을 구하고 enter, leave에 따른 문자열과 붙여서 answer를 업데이트해주면 된다.

[소스 코드]

#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <queue>

using namespace std;

struct info {
    string check;
    string id;
};

vector<string> solution(vector<string> record) {
    vector<string> answer;
    map<string, string> m;
    queue<info> q;
    
    for(string s : record) {
        // 문자열 공백기준으로 자르기
        istringstream str(s);
        string stringbuffer;
        vector<string> temp;
        while(getline(str, stringbuffer, ' ')) {
            temp.push_back(stringbuffer);
        }

        // map에 저장
        if(temp[0]=="Enter") { // enter면 맵에 저장된 값을 변경 후 큐에 push
            m[temp[1]] = temp[2];
            q.push({temp[0], temp[1]});
        } else if(temp[0]=="Leave") { // leave면 큐에 push
            q.push({temp[0], temp[1]});
        } else { // change면 맵에 저장된 값을 변경
            m[temp[1]] = temp[2];
        }
    }

    
    while(!q.empty()) {
        info result = q.front();
        q.pop();
        if(result.check=="Enter") {
            answer.push_back(m[result.id]+"님이 들어왔습니다.");
        } else {
            answer.push_back(m[result.id]+"님이 나갔습니다.");
        }
    }
    
    return answer;
}

0개의 댓글