Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

hwooo

프로그래머스 (C/C++) 42888 : 오픈채팅방 본문

Study/Algorithm

프로그래머스 (C/C++) 42888 : 오픈채팅방

hwooo 2024. 11. 28. 01:03

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;
}