hwooo
프로그래머스 (C/C++) 42888 : 오픈채팅방 본문
https://school.programmers.co.kr/learn/courses/30/lessons/42888
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
풀이
입력 받은 문자열을 명령어, 고유 uid, 닉네임으로 나눈다.
명령어가 Enter, Leave일 때 출력할 문자열을 만들어 저장한다(print). 이 때 닉네임은 고유 uid로 저장해둔다.
명령어가 Enter, Change일 때는 입력받은 닉네임을 map(info)에 저장하여 고유 uid의 이름을 최신 순으로 저장한다.
출력할 문자열들을 순회하며 고유 uid에 대응되는 닉네임을 info에서 대치하여 출력한다.
코드
#include <string>
#include <vector>
#include <map>
using namespace std;
map<string, string> info;
vector<pair<string, string>> print;
// 들어온 문자열 공백 기준으로 파싱
vector<string> parse(string str) {
vector<string> strs;
int idx = 0, len = 0;
for (char c : str) {
if (c == ' ') {
strs.push_back(str.substr(idx, len));
idx += len + 1;
len = 0;
}
else
len++;
}
strs.push_back(str.substr(idx, len));
return strs;
}
// 명령어에 따라 업데이트
void updateInfo(vector<string> strs) {
string command = strs[0], uid = strs[1];
// 입장 시 닉네임 저장
if (command == "Enter") {
print.push_back({uid, "님이 들어왔습니다."});
info[uid] = strs[2];
}
else if (command == "Leave")
print.push_back({uid, "님이 나갔습니다."});
else if (command == "Change")
info[uid] = strs[2];
}
vector<string> solution(vector<string> record) {
vector<string> answer;
for (string r : record) {
vector<string> strs = parse(r);
updateInfo(strs);
}
for (auto p : print)
answer.push_back(info[p.first] + p.second);
return answer;
}
'Study > Algorithm' 카테고리의 다른 글
LeetCode (C/C++, Java) 2290. Minimum Obstacle Removal to Reach Corner (0) | 2024.12.02 |
---|---|
LeetCode (C/C++) 565. Array Nesting (0) | 2024.11.28 |
LeetCode (C/C++) 1306. Jump Game III (0) | 2024.11.27 |
LeetCode (C/C++) 313. Super Ugly Number (0) | 2024.11.26 |
프로그래머스 (C/C++) 86971 : 전력망을 둘로 나누기 (0) | 2024.11.25 |