본문 바로가기

Algorithm/Programmers

[Programmers] C++ LV2_오픈채팅방

#사람마다 푼 방법이 다릅니다. 아 이런 코드도 있구나라는 생각만 가져주시면 감사하겠습니다. 제 코드에 있어서 비효율적인 부분이 있으면 댓글로 남겨놔주시면 참고하여 성장할 수 있도록 하겠습니다!!!

 

하지만!!! 무분별한 비난은 삼가해주세여!

 

오픈채팅방은 처음에는 vector로만 사용하다보니까 제출을 했을 때 마지막 쯤의 케이스에서 시간초과가 났습니다.

물론 해당 문제가 시간이 넉넉한 문제입니다. 그래서 다른 방식으로 생각을 해보려고 했습니다.

 

그래서 생각을 해보니, 기본적으로 사용자 id값이 존재하며, 사용자 id값에 대해서 value값인 username만 변경된다는 것을 알 수 있었습니다. 그래서 map을 사용해서 해당 문제를 풀었습니다.

#include <string>
#include <vector>
#include<iostream>
#include<map>
using namespace std;

vector<string> solution(vector<string> record) {
    map<string, string> tv;
    vector<string> id;
    vector<char> ins;

    for (int a = 0; a < record.size(); a++) {
        record[a] += ' ';
        char tc = record[a][0];
        int ti = 0;
        if (tc == 'L' || tc == 'E') {
            ti = 6;
            ins.push_back(tc);
        }
        else {
            ti = 7;
        }
        string temp = "";
        vector<string> id_name;
        for (int b = ti; b < record[a].size(); b++) {
            if (record[a][b] == ' ') {
                id_name.push_back(temp);
                temp = "";
                continue;
            }
            temp += record[a][b];
        }
        //id_name[0] = id, id_name[1] = name
        if (tc == 'L') {
            id.push_back(id_name[0]);
        }
        else if (tc == 'E') {
            id.push_back(id_name[0]);
            //있을 경우
            if (tv.find(id_name[0]) != tv.end()) {
                //있는데 name이 다른 경우
                if (tv[id_name[0]] != id_name[1]) {
                    tv[id_name[0]] = id_name[1];
                }
            }
            //없는 경우
            else {
                tv.insert({ id_name[0],id_name[1] });
            }
        }
        else if (tc == 'C') {
            tv[id_name[0]] = id_name[1];
        }
    }
    vector<string> answer;
    for (int a = 0; a < ins.size(); a++) {
        string sr = "";
        if (ins[a] == 'L') {
            sr = tv[id[a]] + "님이 나갔습니다.";
        }
        else {
            sr = tv[id[a]] + "님이 들어왔습니다.";
        }
        answer.push_back(sr);
    }
    return answer;
}