본문 바로가기

코딩테스트/c++

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

728x90

 

 

우선 record에 담긴 문자열을 띄어쓰기를 기준으로 나누어야 한다. 그래서 split하는 함수를 따로 구현해주었다.

 

 

각각 유저 아이디와 닉네임을 매칭시키기 위해 map을 사용하였다. record의 문자열들 중 하나를 command라 하면 split하면 command[0]에는 명령어가 들어가고 command[1]에는 유저 아이디가, command[2]에는 닉네임이 들어간다.

만약 문자열의 첫 단어가 'E' 또는 'C'로 시작할 경우 "Enter" 또는 "Change"이므로 map에서 해당 유저 아이디의 value 값을 초기화한다.

 

 

명령어가 Change일 경우에는 출력값이 없으므로 명령어가 Enter일 경우와 Leave일 경우만 설정해주면 된다. 위와 같이 문자열을 띄어쓰기를 기준으로 split 해준 후 명령어에 따라 출력값을 다르게 해주었다.

 

 

전체 코드

#include <string>
#include <vector>
#include <bits/stdc++.h>

using namespace std;

vector<string> split(string str, char c) {
    vector<string> ans;
    stringstream ss(str);
    string tmp;
    
    while(getline(ss,tmp,c)) {
        ans.push_back(tmp);
    }
    return ans;
}

vector<string> solution(vector<string> record) {
    vector<string> answer;
    map<string,string> m;
    
    for(int i=0;i<record.size();i++) {
        vector<string> command;
        command = split(record[i],' ');
        if(command[0][0] == 'E' || command[0][0] == 'C') 
            m[command[1]] = command[2];
    }
    
    for(int i=0;i<record.size();i++) {
        vector<string> command;
        command = split(record[i],' ');
        string usrName = m[command[1]];
        switch(command[0][0]) {
            case 'E':
                answer.push_back(usrName+"님이 들어왔습니다.");
                break;
            case 'L':
                answer.push_back(usrName+"님이 나갔습니다.");
                break;
            default:
                break;
        }
    }
    return answer;
}
728x90
반응형

'코딩테스트 > c++' 카테고리의 다른 글

[백준] 21735번 눈덩이 굴리기  (0) 2021.11.04
[백준] 1966번 프린터 큐  (0) 2021.07.07
[백준] 3273번 두 수의 합  (2) 2021.06.30
[백준] 1406번 에디터  (0) 2021.06.29
백준 c++ 1697번  (2) 2021.01.22