문제 풀이
#include <vector>
#include <string>
#include <sstream> // stringstream
#include <map> // map
using namespace std;
// 문자열을 나누어 저장해주는 함수 split. 뭔지 모르겠으면 python의 split을 찾아보자
vector<string> split(string input, char delimiter) {
vector<string> ans;
stringstream ss(input);
string tmp;
while (getline(ss, tmp, delimiter)) {
ans.push_back(tmp);
}
return ans;
}
vector<string> solution(vector<string> record) {
// record를 나누어 저장할 이차원 배열
vector<vector<string>> uid;
// record를 나누어 uid에 저장.
// {{"Enter", "uid1234", "Muzi"}, {"Enter", "uid4567", "Prodo"},...} 식으로 저장된다.
for (auto it : record) uid.push_back(split(it, ' '));
// 명령어의 실행 순서를 저장해둘 배열
vector<vector<string>> stack;
// 아이디와 이름을 저장해둘 map
map<string, string> namemap;
// it은 uid 내 한 줄("Enter uid1234 Muzi")에서의 각 원소{"Enter", "uid1234", "Muzi"}
for (auto it : uid) {
// it[0]는 명령어 위치. 명령어가 enter나 leave라면
if (it[0] == "Enter" or it[0] == "Leave") {
// 명령어가 들어온 순서대로 스택에 (명령어, 아이디)를 추가
stack.push_back({ it[0], it[1] });
// leave에는 it[2]가 없으므로 enter일때만
if (it[0] == "Enter") {
// map은 key, value 형식으로 지정된다. map[key] = value;
// key = it[1](아이디), value = it[2](이름)
// key는 하나의 value만 갖는다. 즉 같은 key에 다른 value가 들어오면 값을 덮어쓴다.
namemap[it[1]] = it[2];
}
}
// 명령어가 change라면
else {
namemap[it[1]] = it[2];
}
}
// 정답을 저장할 배열
vector<string> answer;
// 명령어의 순서를 저장해둔 배열을 돌면서
for (auto it : stack) {
// 입장 명령어라면
if (it[0] == "Enter") {
// namemap[it[1]]에는 it[1]을 key로 가진 value가 들어있다.
// 즉, 해당 아이디(key)를 가진 이름(value)을 반환한다.
answer.push_back(namemap[it[1]] + "님이 들어왔습니다.");
}
// 퇴장 명령어라면
else {
answer.push_back(namemap[it[1]] + "님이 나갔습니다.");
}
}
return answer;
}
문제 링크
https://programmers.co.kr/learn/courses/30/lessons/42888
코딩테스트 연습 - 오픈채팅방
오픈채팅방 카카오톡 오픈채팅방에서는 친구가 아닌 사람들과 대화를 할 수 있는데, 본래 닉네임이 아닌 가상의 닉네임을 사용하여 채팅방에 들어갈 수 있다. 신입사원인 김크루는 카카오톡 오
programmers.co.kr
'C++ > 프로그래머스' 카테고리의 다른 글
[프로그래머스] [C++] 카펫 (0) | 2021.01.02 |
---|---|
[프로그래머스] [C++] 소수 찾기 (0) | 2020.12.26 |
[프로그래머스] [C++] 모의고사 (0) | 2020.12.11 |
[프로그래머스] [C++] H-Index (0) | 2020.12.09 |
[프로그래머스] [C++] 가장 큰 수 (0) | 2020.12.07 |