Software

(프로그래머스 c++ KAKAO)압축 본문

프로그래머스 알고리즘/KAKAO

(프로그래머스 c++ KAKAO)압축

favorcom 2020. 6. 11. 14:14
728x90
반응형

map을 이용하여 문제를 접근했다.

우선 알파벳 대문자를 모두 사전에 등록을 해야 한다.

그래서 string형 벡터 a에 대문자 알파벳을 모두 넣어준다.

그리고 count는 단어를 나누는 위치를 나타내고, current_num은 사전의 단어 개수를 나타낸다.

<string, int>형 map을 선언했으니 알파벳 대문자와 인덱스를 넣어주도록 한다.(1 ~ 26까지)

 

이제 while문으로 단어를 압축하자.

현재 입력 w, 다음 글자 c, 추가할 단어 wc를 선언하여 값을 넣어준다.

그리고 반복자를 각각 선언하여 사전에서 찾도록 한다.

 

만약 w가 사전에 있다면 answer에 인덱스를 넣어주고, count 값을 늘려주거나 1로 초기화한다.

wc의 반복자를 이용하여 count를 조절한다.

만약 wc가 사전에 없다면 count를 1로 바꿔주고 msg에서 지우도록 한다.

사전에 있다면 count를 계속 늘려준다.

 

c가 msg의 끝에 다다르면 answer에 마지막 단어의 인덱스를 넣어주고 while문을 빠져나가면 끝!

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

vector<int> solution(string msg) {
    vector<int> answer;
    map<string, int> word;
    vector<string> a = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    int count = 1, current_num = 27;
    
    for(int i = 0; i < 26; i++)
        word.insert(make_pair(a[i], i + 1));
    while(1)
    {
        string w = msg.substr(0, count);
        string c = msg.substr(count, 1);
        string wc = w + c;
        auto tmp_w = word.find(w);
        auto tmp_c = word.find(c);
        auto tmp_wc = word.find(wc);
        
        if(tmp_w != word.end())
        {
            if(tmp_wc != word.end())
            {
                if(count < msg.size())
                    count++;
            }
            else
            {    
                answer.push_back(tmp_w->second);
                word.insert(make_pair(wc, current_num++));
                msg.erase(0, count);
                count = 1;
            }
        }
        if(c == "\0")
        {
            answer.push_back(tmp_w->second);
            break;
        }
    }
    return answer;
}
728x90
반응형