[프로그래머스/C++]Lv.2 - [3차]압축

YH J·2023년 9월 27일
0

프로그래머스

목록 보기
159/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/17684

내 풀이

map을 이용했다.
map에 일단 알파벳들을 index와 함께 사전순으로 저장했다.
msg를 for문으로 순회하면서 s에 한 알파벳씩 추가하는데
msg[i]를 추가한 s가 사전에 없다면 answer에 dic[s] 값을 추가하고 s는 msg[i]를 더한 뒤 사전에 등록한다. s는 초기화하고 i--해준다.
사전에 이미 있다면 s에 msg[i]를 더한다.
다 끝내고 s가 남아있다면 사전에서 찾아 추가해준다.

내 코드

#include <string>
#include <vector>
#include <map>

using namespace std;

vector<int> solution(string msg) {
    vector<int> answer;
    
    map<string,int> dic;
    int index = 0;
    for(index; index < 26; index++)
    {
        string s;
        s += 'A' + index;
        dic[s] = index + 1;
    }
    
    string s;
    
    for(int i = 0; i < msg.length(); i++)
    {
        if(dic.find(s+msg[i]) == dic.end())
        {
            answer.push_back(dic[s]);
            s += msg[i];
            dic[s] = index++ + 1;
            s = "";
            i--;
        }
        else
            s += msg[i];
    }
    
    if(s.length())
        answer.push_back(dic[s]);
    
    return answer;
}

다른 사람의 풀이

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

vector<int> solution(string msg) {
    vector<int> ans;
    map<string, int> mymap;
    string str = "";
    for(int i = 0; i < 26; ++i){
        str += (i+65);
        mymap[str.substr(i,1)] = i+1;
    }
    for(int i = 0; i < msg.size();){
        str = "";
        while(i < msg.size() && mymap.find(str + msg[i]) != mymap.end())
            str += msg[i++];
        ans.push_back(mymap[str]);
        if(i < msg.size()) mymap[str + msg[i]] = mymap.size() + 1;
    }
    return ans;
}

다른 사람의 풀이 해석

똑같이 map에 사전을 등록해놓고
for문 안에 while을 사용했다.
str+msg[i]가 사전에 없을때까지 str을 더해간다.
사전에 없으면 나와서 사전에 있는 str을 answer에 push_back해주고 사전에 str + msg[i]를 등록해준다.

profile
게임 개발자 지망생

0개의 댓글