ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [프로그래머스] 오픈 채팅방
    알고리즘/프로그래머스 2021. 7. 19. 11:51

    문제 링크

     

    풀이

    C++에는 문자열을 구분자로 친절하게 잘라주는 함수가 없습니다. 대신에 string 클래스에 find 함수를 이용해서 만들 수 있습니다. 여기에서는 공백이 구분자인데, 어떤 구분자가 주어져도 자를 는 split 함수를 외워두면 다른 문제 풀이에도 도움 될 것 같습니다.

     

    문제의 답은 변경이 모두 적용된 최종 상태를 가지고 시스템 메시지를 출력하는 것입니다. Enter, Leave 메시지는 출력하지만 Change는 출력하지 않습니다. 사용자 아이디를 키로 하고 닉네임을 값으로 해 최종 상태를 반영했습닙다. 이를 위해 map을 사용했습니다. unordered_map을 사용해도 됩니다.. map은 균형 이진 트리인 red-black tree로, unordered_map은 해쉬로 구현됐습니다. 데이터 양이 적당할 때는 unordered_map이 조금 더 빠르지만 데이터가 많아지면 해쉬 버킷 충돌이 일어날 확률 높아지므로 성능에 조금씩 떨어집니다.

     

    코드

    #include <string>
    #include <vector>
    #include <map>
    using namespace std;
    
    vector<string> split(string str, string delim)
    {
        vector<string> result;
        size_t pos = 0, curr = 0;
        while (string::npos != pos)
        {
            pos = str.find(delim, curr);
            string temp = str.substr(curr, pos - curr);
            result.push_back(temp);
            curr = pos + 1;
        }
        return result;
    }
    
    vector<string> solution(vector<string> record) 
    {
        vector<string> answer;
        string delim = " ";
        map<string, string> m;
        for (string str : record)
        {
            auto result = split(str, delim);
            if (2 == result.size()) continue;      
            else
                m[result[1]] = result[2];
        }
        for (string str : record)
        {
            string temp;
            auto result = split(str, delim);
            auto status = result[0];
            if ("Enter" == status)
                temp = m[result[1]] + "님이 들어왔습니다.";
            else if ("Leave" == status)
                temp = m[result[1]] + "님이 나갔습니다.";
            else continue;
            answer.push_back(temp);
        }
        return answer;
    }

    댓글

Designed by Tistory.