https://programmers.co.kr/learn/courses/30/lessons/42888
코딩테스트 연습 - 오픈채팅방
오픈채팅방 카카오톡 오픈채팅방에서는 친구가 아닌 사람들과 대화를 할 수 있는데, 본래 닉네임이 아닌 가상의 닉네임을 사용하여 채팅방에 들어갈 수 있다. 신입사원인 김크루는 카카오톡 오
programmers.co.kr
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
vector<string> solution(vector<string> record) {
const char ENTER = 'E', LEAVE = 'L', CHANGE = 'C';
unordered_map<string, string> id_map;
string command, uid, nick;
// 입장 또는 변경일 때 id_map맵에 <uid, nick> 저장
for (string line : record)
{
stringstream ss(line);
ss >> command;
if (command[0] == ENTER || command[0] == CHANGE)
{
ss >> uid;
ss >> nick;
id_map[uid] = nick;
}
}
// 입장 또는 퇴장일 때 answer벡터에 nick + 메시지 저장
vector<string> answer;
for (string line : record)
{
stringstream ss(line);
ss >> command;
ss >> uid;
if (command[0] == ENTER)
{
answer.push_back(id_map[uid] + "님이 들어왔습니다.");
}
else if (command[0] == LEAVE)
{
answer.push_back(id_map[uid] + "님이 나갔습니다.");
}
}
return answer;
}
구현 아이디어 자체는 크게 어려운 것이 아니었지만
c++로 문자열을 파싱하는게 처음이라서 많이 버벅댔다.
char*과 strcpy, strtok을 이용하는 방법이 더 빠르지만
stringstream을 활용하는게 훨씬 코드가 깔끔하고 직관적이다.
stringstream 사용법 참고:
http://www.cplusplus.com/reference/sstream/stringstream/stringstream/
stringstream::stringstream - C++ Reference
initialization (2)explicit stringstream (const string& str, ios_base::openmode which = ios_base::in | ios_base::out);
www.cplusplus.com
좀더 상세한 설명 :
http://www.cplusplus.com/reference/sstream/stringstream/
stringstream - C++ Reference
class std::stringstream typedef basic_stringstream stringstream; Input/output string stream Stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be a
www.cplusplus.com
'Algorithm > 프로그래머스' 카테고리의 다른 글
[프로그래머스]2018 KAKAO BLIND RECRUITMENT : 방금그곡 (level 2)(c++) (0) | 2020.05.26 |
---|---|
[프로그래머스]2019 KAKAO BLIND RECRUITMENT : 후보키 (level 2)(c++) (0) | 2020.05.25 |
[프로그래머스]2018 KAKAO BLIND RECRUITMENT : 캐시 (level 2)(c++) (0) | 2020.05.25 |
[프로그래머스]2018 KAKAO BLIND RECRUITMENT : 프렌즈4블록(level 2)(c++) (0) | 2020.05.25 |
[프로그래머스]2018 KAKAO BLIND RECRUITMENT : 뉴스 클러스터링 (level 2)(c++) (0) | 2020.05.25 |
댓글