본문 바로가기

Algorithm/카카오기출

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

문제

 

 

 

풀이 1

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

vector<string> solution(vector<string> record) {
    //map, vector
    unordered_map<string, string> map;
    vector<vector<string>> user;
    vector<string> answer;
    for(int i=0; i<record.size(); i++){
        vector<string> vec;
        stringstream stream1;
        stream1.str(record[i]);
        string id, state, name;
        stream1 >> state >> id >> name;
        
        if(state != "Change"){
            vec.push_back(state);
            vec.push_back(id);
            user.push_back(vec);
        }
        if(state != "Leave") map[id] = name;
    }
    for(auto a : user){
        string s;
        s += map[a[1]] + "님이 ";
        a[0] == "Enter" ? s+= "들어왔습니다." : s+= "나갔습니다.";
        answer.push_back(s);
    }
    
    
    return answer;
}

 

 

 

풀이 2

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

vector<string> solution(vector<string> record) {
    unordered_map<string, string> map;
    vector<string> answer;
    string id, state, name;
    for(int i=0; i<record.size(); i++){
        stringstream stream1;
        stream1.str(record[i]);
        stream1 >> state >> id >> name;
        if(state != "Leave") map[id] = name;
    }
    for(auto a : record){
        string s = "";
        stringstream stream1;
        stream1.str(a);
        stream1 >> state >> id;
        if(state == "Change") 
            continue;
        s += map[id] + "님이 ";
        state == "Enter" ? s+= "들어왔습니다." : s+= "나갔습니다.";
        answer.push_back(s);
    }
    
    
    return answer;
}

user 벡터는 필요 없는 것 같아 빼준 후 다시 구현했다.

 

 


 

다른 사람 풀이

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


vector<string> solution(vector<string> record) {
    vector<string> answer;
    string command;
    string ID;
    string uid;
   map<string,string> m;


    for(string input:record)
    {
        stringstream ss(input);
        ss>>command;
        ss>>uid;
        if(command=="Enter" || command=="Change")
        {
            ss>>ID;
            m[uid]=ID;
        }
    }

   for(string input:record)
    {
        stringstream ss(input);
        ss>>command;
        ss>>uid;
        if(command=="Enter")
        {
         ID=(m.find(uid)->second);

            string temp = ID+"님이 들어왔습니다.";
         answer.push_back(temp);

        }
      else if(command=="Leave")
      {
         ID=(m.find(uid)->second);
            string temp = ID+"님이 나갔습니다.";
         answer.push_back(temp);
      }
    }
    return answer;
}