문제 URL
https://school.programmers.co.kr/learn/courses/30/lessons/42888
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
[문제 설명]
이 문제는 채팅방에 들어오고 나가거나, 닉네임을 변경한 기록이 담긴 문자열 배열 record가 매개변수로 주어질 때, 모든 기록이 처리된 후, 최종적으로 방을 개설한 사람이 보게 되는 메시지를 문자열 배열 형태로 return 하는 함수를 작성하는 문제이다.

[문제 풀이]
Hash map을 사용하여 풀 수 있었다.
사용자의 id(=uid)와 이름을 key와 value로 해시 맵에 저장해 두고 만약 상태가 Change라면 key(uid)에 따른 value(이름)를 변경한다.
위 과정을 record의 모든 원소에 적용한 뒤 마지막에 상태(Enter, Leave)에 따라 해시 맵의 키를 출력해 주면 된다.

#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
vector<string> solution(vector<string> record) {
vector<string> answer;
unordered_map<string,string> hash_map; // key=Id, value=name
vector<pair<string,string>> action_id; // Action, Id 정보 저장
for(auto s:record){
int start = 0;
vector<string> actionIdName;
for(int i=0;i<s.length();i++){
if(s[i]==' '){ // 공백을 기준으로 분리(마지막은 저장되지 않음 ex. Muzi)
actionIdName.push_back(s.substr(start,i-start));
start=i+1;
}
}
if(actionIdName[0] != "Leave") // Enter, Change인 경우
hash_map[actionIdName[1]] = s.substr(start);
else // Leave인 경우
actionIdName.push_back(s.substr(start));
action_id.push_back({actionIdName[0], actionIdName[1]});
}
for(auto iter : action_id){
string action = iter.first;
string id = iter.second;
if(action=="Enter")
answer.push_back(hash_map[id]+"님이 들어왔습니다.");
else if(action=="Leave")
answer.push_back(hash_map[id]+"님이 나갔습니다.");
}
return answer;
}