[프로그래머스/C++] 압축

최대 1 분 소요

1.문제 링크

압축



2. 풀이 전 계획과 생각

  • map 자료구조 사용



3. 풀이

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

vector<int> solution(string msg) {
    vector<int> answer;
    map<string, int> m;
    for(int i=1; i<=26;i++){
        char c = i+64;
        string str(1, c);
        m.insert({str,i});
    }
    int maxlen = 1;
    int index=0;
    int value = 27;
    while(1){
        for(int i=maxlen; i>=1; i--){
            if(m.find(msg.substr(index, i))!=m.end()){
                int temp = m[msg.substr(index,i)];
                answer.push_back(temp);
                if(index!=msg.size()-1){
                    string newstr = msg.substr(index, i+1);
                    m.insert({newstr, value});
                    maxlen++;
                    value++;
                }
                index = index + i;
                break;
            }
        }
        if(index>msg.size()-1) break;
    }
    return answer;
}

maxlen 변수는 사전에 추가된 가장 긴 문자열 길이로 각 문자마다 maxlen부터 1까지 substr해서 map 자료형에 해당 문자열이 있는지 확인하고 해당 값을 삽입하고 +1 더 긴 문자열을 map 자료형에 삽입한다.



4. 풀이하면서 고민했던 점

  • char을 string으로 바꾸는 방법 char을 string으로 바꿀 때, string(length, char);을 해야한다.



5. 문제를 풀고 알게된 개념 및 소감