Coding Test/programmers
[프로그래머스] 오픈채팅방 C++
owls
2023. 10. 25. 14:13
728x90
문제 설명
제한 사항
- record는 다음과 같은 문자열이 담긴 배열이며, 길이는 1 이상 100,000 이하이다.
- 다음은 record에 담긴 문자열에 대한 설명이다.
- 모든 유저는 [유저 아이디]로 구분한다.
- [유저 아이디] 사용자가 [닉네임]으로 채팅방에 입장 - "Enter [유저 아이디] [닉네임]" (ex. "Enter uid1234 Muzi")
- [유저 아이디] 사용자가 채팅방에서 퇴장 - "Leave [유저 아이디]" (ex. "Leave uid1234")
- [유저 아이디] 사용자가 닉네임을 [닉네임]으로 변경 - "Change [유저 아이디] [닉네임]" (ex. "Change uid1234 Muzi")
- 첫 단어는 Enter, Leave, Change 중 하나이다.
- 각 단어는 공백으로 구분되어 있으며, 알파벳 대문자, 소문자, 숫자로만 이루어져있다.
- 유저 아이디와 닉네임은 알파벳 대문자, 소문자를 구별한다.
- 유저 아이디와 닉네임의 길이는 1 이상 10 이하이다.
- 채팅방에서 나간 유저가 닉네임을 변경하는 등 잘못 된 입력은 주어지지 않는다.
입출력 예
record | result |
["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"] | ["Prodo님이 들어왔습니다.", "Ryan님이 들어왔습니다.", "Prodo님이 나갔습니다.", "Prodo님이 들어왔습니다."] |
풀이
user id를 기준으로 user name을 출력하도록 하면 된다.
들어온 순서, 나간 순서는 유지되어야 하기 때문에 user id기준으로 unordered_map에 저장해놓고,
변경된 user name이 적용될 수 있도록 마지막에 user id에 매칭된 값을 출력하는 방법으로 풀었습니다.
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
void myParser(const string& str, vector<string> &result){
string s = str;
int pos = 0;
string token("");
while( (pos = s.find(" ")) != string::npos){
token = s.substr(0, pos);
result.push_back(token);
s.erase(0, pos + 1);
}
result.push_back(s);
}
vector<string> solution(vector<string> record) {
unordered_map<string, string> table;
vector<pair<string, string>> vec;
for(const auto& rec : record){
vector<string> value;
myParser(rec, value);
if( value[0][0] == 'E'){
table[value[1]] = value[2];
vec.push_back({"E", value[1]});
}
else if(value[0][0] == 'L'){
vec.push_back({"L", value[1]});
}
else if(value[0][0] == 'C'){
table[value[1]] = value[2];
}
}
vector<string> answer;
for(const auto& it : vec){
string s("");
if(it.first == "E"){
s = table[it.second]+"님이 들어왔습니다." ;
answer.push_back(s);
}
else if(it.first == "L"){
s = table[it.second]+"님이 나갔습니다.";
answer.push_back(s);
}
}
return answer;
}
다른 풀이
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
void myParser(const string& str, vector<string>& value){
string s = str, token("");
int pos = 0;
while( (pos = s.find(" ")) != string::npos ){
token = s.substr(0, pos);
value.push_back(token);
s.erase(0, pos + 1);
}
value.push_back(s);
}
vector<string> solution(vector<string> record) {
unordered_map<string, string> msg;
unordered_map<string, string> nickname;
vector<pair<string, string>> vec;
msg["Enter"] = "님이 들어왔습니다.";
msg["Leave"] = "님이 나갔습니다.";
for(string& s : record){
vector<string> value;
myParser(s, value);
if(value.size() == 3){
nickname[value[1]] = value[2];
}
if(value[0][0] == 'E'){
vec.push_back({value[0], value[1]});
}
else if(value[0][0] == 'L'){
vec.push_back({value[0], value[1]});
}
}
vector<string> answer;
for(const auto& it : vec){
string str = nickname[it.second] + msg[it.first];
answer.push_back(str);
}
return answer;
}
728x90