๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ‘จ‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

์ž…๋ ฅ ๋ฐ์ดํ„ฐ ๊ฐœ์ˆ˜๊ฐ€ ์ตœ๋Œ€ 10๋งŒ ๊ฐœ์ด๊ธฐ์— ๊ฒ€์ƒ‰์„ ๋น ๋ฅด๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด, ํ•ด์‹œ(Hash)๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ตฌํ˜„ํ•˜๋Š” ๋ถ€๋ถ„์ด ์กฐ๊ธˆ ๊ธธ ๋ฟ, ๋ฌธ์ œ ์ž์ฒด๋Š” ์–ด๋ ต์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.

 

  1. for๋ฌธ์œผ๋กœ record๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ, <id, UserData> ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ํ•ด์‹œ์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
  2. ๋‹ค์‹œ for๋ฌธ์œผ๋กœ record๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ, ๊ฐ ๋ช…๋ น์–ด(Enter, Leave, Change)์— ํ•ด๋‹นํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ˆ˜ํ–‰ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
using namespace std;
const int INSTRUCTION = 0;
const int ID = 1;
const int NICKNAME = 2;

unordered_map<string, string> ChatMessages { {"Enter", "๋‹˜์ด ๋“ค์–ด์™”์Šต๋‹ˆ๋‹ค."}, {"Leave", "๋‹˜์ด ๋‚˜๊ฐ”์Šต๋‹ˆ๋‹ค."} };

class User {
public:
    User() { }
    User(string id, string nickName) : _id(id), _nickName(nickName) { }
    string GetMessage(const string& instruction)   { return _nickName + ChatMessages[instruction]; }
    void ChangeNickName(const string& newNickName) { _nickName = newNickName; }
    string GetId()       { return _id; }
    string GetNickName() { return _nickName; }

private:
    string _id;
    string _nickName;
};


vector<string> Split(const string& log) {
    vector<string> result;
    stringstream tokenizer(log);
    string buffer;

    while (getline(tokenizer, buffer, ' '))
        result.push_back(buffer);
    return result;
}


vector<string> solution(vector<string> record) {
    vector<string> answer;
    unordered_map<string, User> users;

    // ์œ ์ € ๋“ฑ๋ก ๋ฐ ๋‹‰๋„ค์ž„ ๋ณ€๊ฒฝ ์ž‘์—…
    for (const auto log : record) {
        vector<string> contents = Split(log);
        auto it = users.find(contents[ID]);
        
        if (contents[INSTRUCTION] == "Leave")
            continue;

        // ์ฒซ ์ ‘์†
        if (it == users.end()) {
            users.emplace(contents[ID], User(contents[ID], contents[NICKNAME]));
            continue;
        }
        
        // ๋‚˜๊ฐ”๋‹ค ๋“ค์–ด์™”๊ฑฐ๋‚˜, ๋‹‰๋„ค์ž„์„ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒฝ์šฐ
        if (contents[INSTRUCTION] == "Enter" or contents[INSTRUCTION] == "Change")
            users[contents[ID]].ChangeNickName(contents[NICKNAME]);
    }

    // ์ถœ๋ ฅ ๊ฒฐ๊ณผ๋ฌผ ๋‹ด๊ธฐ
    for (const auto log : record) {
        vector<string> informations = Split(log);
        if(informations[INSTRUCTION] != "Change")
            answer.emplace_back(users[informations[ID]].GetMessage(informations[INSTRUCTION]));
    }

    return answer;
}

 

 

728x90
๋ฐ˜์‘ํ˜•