본문 바로가기

코딩테스트 연습/programmers

[Programmers] 프로그래머스 오픈채팅방(c++)

https://programmers.co.kr/learn/courses/30/lessons/42888

 

코딩테스트 연습 - 오픈채팅방

오픈채팅방 카카오톡 오픈채팅방에서는 친구가 아닌 사람들과 대화를 할 수 있는데, 본래 닉네임이 아닌 가상의 닉네임을 사용하여 채팅방에 들어갈 수 있다. 신입사원인 김크루는 카카오톡 오

programmers.co.kr

코딩테스트 연습 > 2019 KAKAO BLIND RECRUITMENT > 오픈채팅방

 

 

 

이중 for문과 벡터를 이용해서 풀었더니 실패했다. (메모리 초과, signal: segmentation fault  ) 

키 값에 의존하여 닉네임 값을 변경하면 되니까 , 정렬이 필요없는 unordered_map을 사용했다.

그런데 아래처럼 string.push_back(chat[i][2])를 추가 후 나머지 문자를 추가했을때 모든 답이 signal: segmentation fault 라서 뭔가 또 잘못된건가 고민했었는데, 

string text=""변수를 두고 text에 문장을 넣은 후, 문장이 완성 될때 result에 push하니까 해결됐다.

왜 이런건지 생각해보니,

result에 닉네임 (id_name[chat[i][1]])를 push하면, result[i] += 할때의 i와 push할때의 i가 다를 수도 있어서 배열 참조가 제대로 되지 않기 때문인 것 같다.


틀린 코드

    for(int i=0;i<record.size();i++){
        if(chat[i][0] == "Change") continue;
        
        result.push_back(id_name[chat[i][1]]);
        
        if(chat[i][0] == "Enter") result[i] += "님이 들어왔습니다.";
        else if(chat[i][0] == "Leave") result[i] += "님이 나갔습니다.";
    }

 

 


main포함 코드(c++)

#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
using namespace std;

vector<string> solution(vector<string> record) {
    vector<vector<string>> chat(record.size());
    vector<string> result;
    unordered_map<string, string> id_name;
    
    for(int i=0;i<record.size();i++){
        istringstream ss(record[i]);
        string word;
        while (getline(ss, word, ' ')) {
            chat[i].push_back(word);
        }
    }
    //닉네임 변경 체크
    for(int i=0;i<record.size();i++){
        if(chat[i][0] != "Leave") id_name[chat[i][1]] = chat[i][2];
    }

    for(int i=0;i<record.size();i++){
        string text = "";
        if(chat[i][0] == "Change") continue;
        
        text += id_name[chat[i][1]];
        if(chat[i][0] == "Enter") text += "님이 들어왔습니다.";
        else if(chat[i][0] == "Leave") text += "님이 나갔습니다.";
        result.push_back(text);
    }
    
    
    return result;
}

int main(){
    
    vector<string> record = {"Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"};
    
    solution(record);
    return 0;
}