본문 바로가기

PS/프로그래머스

프로그래머스 2018 KAKAO BLIND RECRUITMENT - 압축[JAVA]

문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/17684

 

프로그래머스

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

programmers.co.kr

코드:

 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * dict: Key: 단어 value: 색인 번호
 * 1. 사전 초기화
 * 2. 사전에서 현재 입력(w)과 일치하는 가장 긴 문자열 찾기. -> map.containsKey(w) = true
 * 3. w에 해당하는 색인 번호 출력
 * 4. w + c(다음 문자. 2번에서 c를 찾을 수 있다)가 사전에 없으면 추가
 * 5. c부터 다시 2 시작*
 */

class Solution {
    public int[] solution(String msg) {
        List<Integer> list = new ArrayList<>();
        HashMap<String, Integer> dict = new HashMap<>();
        int index;
        char c = 'A';
        for (index = 1; index <= 26; index++) {
            dict.put(String.valueOf(c), index);
            c += 1;
        }
        int i = 0; // w의 처음 index
        while (i < msg.length()) {
            int j = i + 1;
            while (j <= msg.length()) {
                if(dict.containsKey(msg.substring(i, j))) j++;
                else break;
            }
            list.add(dict.get(msg.substring(i, j - 1)));
            if (j <= msg.length()) {
                dict.put(msg.substring(i, j), index++);
            }
            i = j - 1;
        }

        int[] answer = new int[list.size()];
        for (int j = 0; j < list.size(); j++) {
            answer[j] = list.get(j);
        }
        return answer;
    }
}

public class Main {

    public static void main(String[] args) {
        Solution sol = new Solution();
        String msg = "KAKAO";
        int[] answer = sol.solution(msg);
        for (int i : answer) {
            System.out.println("i = " + i);
        }
    }
}