프로그래머스 42888 - 오픈채팅방
생각 및 접근
vector<pair<string, string>> logs;
- 유저들이 나가거나, 들어오거나를 기록하는
logs
- 앞의 string은 uid를, 뒤의 string은 Enter, 혹은 Leave를 저장할 예정
- 유저들이 나가거나, 들어오거나를 기록하는
map<string, string> m;
- 유저들의 이름을 저장할 map 선언
- 앞의 string은 uid를, 뒤의 string은 유저들의 닉네임을 저장.
주어진
vector<string> record
를 분석한다.action[0]
에는 행동을 담았다. (Leave, Enter, Change)action[1]
에는 uid를 담았다.action[2]
에는 유저들의 닉네임을 담았다.- 만약 행동이 떠나거나, 들어오는 것이었다면
logs
에 저장해두어야 한다.if(action[ACT] == "Enter" || action[ACT] == "Leave"){ logs.push_back(make_pair(action[ID], action[ACT])); }
- 만약 행동이 들어오거나, 이름을 바꾸는 행위라면, 닉네임이 바뀌었을 수 있기 때문에,
m
을 바꿔준다.if(action[ACT] == "Enter" || action[ACT] == "Change"){ m[action[ID]] = action[NAME]; }
최종적으로
answer
의 형태로 변환하기 위해, 아래 코드와 같은 과정을 거친다.lSize = logs.size(); for(int i = 0; i < lSize; i++){ string temp = m[logs[i].first]; if(logs[i].second == "Enter") temp.append("님이 들어왔습니다."); else temp.append("님이 나갔습니다."); answer.push_back(temp); } return answer;
코드
#include <bits/stdc++.h>
#define ACT 0
#define ID 1
#define NAME 2
using namespace std;
vector<string> answer;
vector<pair<string, string>> logs;
map<string, string> m;
vector<string> solution(vector<string> record) {
int rSize = record.size();
int lSize;
for(int i = 0; i < rSize; i++){
int k = 0;
string action[3];
for(int j = 0; record[i][j] != '\0'; j++){
if(record[i][j] == ' ') k++;
else action[k].push_back(record[i][j]);
}
if(action[ACT] == "Enter" || action[ACT] == "Leave"){
logs.push_back(make_pair(action[ID], action[ACT]));
}
if(action[ACT] == "Enter" || action[ACT] == "Change"){
m[action[ID]] = action[NAME];
}
}
lSize = logs.size();
for(int i = 0; i < lSize; i++){
string temp = m[logs[i].first];
if(logs[i].second == "Enter")
temp.append("님이 들어왔습니다.");
else
temp.append("님이 나갔습니다.");
answer.push_back(temp);
}
return answer;
}
채점 결과
'Coding Test > programmers' 카테고리의 다른 글
프로그래머스 42890 - 후보키 (c++) (0) | 2020.09.18 |
---|---|
프로그래머스 42889 - 실패율 (c++) (0) | 2020.09.11 |
프로그래머스 42628 - 이중우선순위큐 (c++) (0) | 2020.07.31 |
프로그래머스 42629 - 라면공장 (c++) (0) | 2020.07.31 |
프로그래머스 42626 - 더 맵게 (c++) (0) | 2020.07.31 |