Study Record

[프로그래머스] Level2 - 오픈채팅방 본문

알고리즘

[프로그래머스] Level2 - 오픈채팅방

초코초코초코 2021. 12. 1. 22:55
728x90
#include <string>
#include <vector>
#include <map>

using namespace std;
string getUid(string str) {
    int start = 0, count = 0, end = 0;
    while (str[start] != ' ') start++;
    end = ++start;
    while (end < str.length() && str[end] != ' ') {
        end++;
        count++;
    }
    return str.substr(start, count);
}
string getNickname(string str) {
    int start = str.length() - 1;
    while (str[start] != ' ') start--;
    return str.substr(start + 1, str.length() - 1 - start);
}
vector<string> solution(vector<string> record) {
    vector<string> answer;
    map<string, string> uidToNick;
    vector<pair<string, string>> answerTmp;  // ([enter | leave], uid)
    
    for(int i=0; i<record.size(); i++){
        if(record[i][0] == 'E'){
            // Enter 인 경우 uid, nickname 등록
            string uid = getUid(record[i]);
            if (uidToNick.find(uid) != uidToNick.end()) {
                // 이미 존재
                uidToNick[uid] = getNickname(record[i]);
            } else {
                // 존재하지 않음
                uidToNick.insert({uid, getNickname(record[i])});
            }
            answerTmp.push_back(make_pair("님이 들어왔습니다.", uid));
        } else if(record[i][0] == 'C'){
            // nickname 을 바꾸는 경우
            string uid = getUid(record[i]);
            uidToNick[uid] = getNickname(record[i]);
        } else {
            // Leave 의 경우
            string uid = getUid(record[i]);
            answerTmp.push_back(make_pair("님이 나갔습니다.", uid));
        }
    }
    
    // answer 만들기
    for(int i=0; i<answerTmp.size(); i++){
        answer.push_back(uidToNick[answerTmp[i].second] + answerTmp[i].first);
    }
    
    return answer;
}
728x90