Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코딩응급실

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

Java

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

Daeryuk Kim 2024. 3. 17. 22:25
import java.util.*;
public class Solution {
    public int[] solution(String msg) {
        // 결과를 저장할 ArrayList 선언 (동적 크기 조정이 필요하기 때문)
        ArrayList<Integer> resultList = new ArrayList<>();
        // 사전 초기화: 각 알파벳에 대응하는 색인 번호 저장
        Map<String, Integer> dictionary = new HashMap<>();
        for (int i = 0; i < 26; i++) {
            char ch = (char) ('A' + i);
            dictionary.put(String.valueOf(ch), i + 1);
        }

        for (int i = 0; i < msg.length();) {
            // 사전에서 현재 입력과 일치하는 가장 긴 문자열 w 찾기
            String w = "";
            int index = 0;
            for (int j = i + 1; j <= msg.length(); j++) {
                String current = msg.substring(i, j);
                if (dictionary.containsKey(current)) {
                    w = current;
                    index = dictionary.get(current);
                } else {
                    // w+c를 사전에 등록
                    dictionary.put(current, dictionary.size() + 1);
                    break;
                }
            }
            // w에 해당하는 사전의 색인 번호를 결과에 추가
            resultList.add(index);
            // 입력에서 w를 제거 (다음 검색 시작 위치 업데이트)
            i += w.length();
        }

        // 결과를 배열로 변환하여 반환
        int[] answer = new int[resultList.size()];
        for (int i = 0; i < answer.length; i++) {
            answer[i] = resultList.get(i);
        }
        
        return answer;
    }

    // 메인 함수로 테스트 가능
    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] result = sol.solution("KAKAO");
        
        System.out.println(Arrays.toString(result));
    }
}

0, 1 = K
0, 2 = KA => 사전 뒤에 차곡차곡 추가!
index: 11


1, 2 = A
1, 3 = AK => 사전 뒤에 차곡차곡 추가!
index: 1


2, 3 = K
2, 4 = KA  (넌, 사전 27번째에 있지 않았니?!)
2, 5 = KAO => 사전 뒤에 차곡차곡 추가!
index: 27


4, 5 = O
index: 15


결과: [11, 1, 27, 15]