본문 바로가기

코딩테스트/프로그래머스

[프로그래머스] [3차] 압축

728x90
반응형


🔗 문제 링크

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


728x90

👩‍💻 코드

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

using namespace std;

vector<int> solution(string msg) {
    vector<int> answer;
    map<string, int> dictionary;
    int i = 0;
    int len = 0;
    int index = 27;
    string key;
    
    for(char c = 'A'; c <= 'Z'; c++){
        dictionary[string(1, c)] = c - 64; 
    }
    
    while(i < msg.size()){
        key = msg[i];
        
        for(; dictionary.find(key) != dictionary.end(); len++){
            key += msg[++i];
        }
        
        answer.push_back(dictionary[key.substr(0, len)]);
        dictionary[key] = index++;
        key = "";
        len = 0;
    }
    
    return answer;
}

📝 풀이

우선 사전(map)에 key를 단어, value를 색인 번호로 지정하고 영문자 A부터 Z까지 초기화합니다.

 

msg의 처음부터 글자가 등록되어 있지 않을 때까지 key에 문자를 추가하고 i값을 증가시킵니다.

이 때, 실행 횟수를 카운팅해두고 key값을 잘라 색인 번호를 출력해줍니다.

자르지 않은 key값은 사전에 새로 추가합니다.

⭐ 예시 : KAKAO⭐

key 반복문 실행 후 key len
K KA 1
A AK 1
K KAO 2
O O 1

 

최종적으로 색인 번호를 담고 있는 answer을 return 합니다.

728x90
반응형