프로그래머스 - 오픈채팅방

well-life-gm·2021년 11월 14일
0

프로그래머스

목록 보기
49/125

프로그래머스 - 오픈채팅방

먼저 stringstream을 이용해서 띄어쓰기 기준으로 나눠서 ['Enter', 'uid1234', 'Muzi'] 의 형태로 record를 처리해준다.
Change가 들어오는 경우 이전에 들어온 닉네임들도 변경을 해줘야하기 때문에, Enter시 들어온 uid들을 모두 map으로 관리해준다. 그리고 Change가 들어오는 순간 해당 uid(Key)의 닉네임(Value)을 변경해주면 된다.

주어진 record를 모두 처리한 뒤, map에 존재하는 Key:Value 대해서 결과값을 출력해주면된다.

다른 분들의 코드도 이와 비슷한 것 같다.

코드는 아래와 같다.

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

using namespace std;

vector<string> solution(vector<string> record) {
    vector<string> answer;
    vector<string> uidV;
    vector<int> opV;
    map<string, string> myMap;

    for(int s=0;s<record.size();s++) {
        stringstream ss(record[s]);
        vector<string> op;
        string str;
        while(ss >> str) 
            op.push_back(str);
        
        if(!op[0].compare("Enter")) {
            opV.push_back(0);
            uidV.push_back(op[1]);
            myMap[op[1]] = op[2];
        } else if(!op[0].compare("Leave")){ 
            opV.push_back(1);
            uidV.push_back(op[1]);
        } else 
            myMap[op[1]] = op[2];
    }
    for(int i=0;i<opV.size();i++) {
        string name = myMap.find(uidV[i])->second;
        string s = opV[i] ? name + "님이 나갔습니다." : name + "님이 들어왔습니다.";
        answer.push_back(s);
    }
    return answer;
}

결과

profile
내가 보려고 만든 블로그

0개의 댓글