본문 바로가기

코딩테스트/programmers

압축

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

 

프로그래머스

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

programmers.co.kr

 

사전이 배열처럼 보이긴 하지만, 매번 사전을 탐색해야 하는 만큼 문자-인덱스 구성의 HashMap을 사용했다. 

 

주어진 문자열을 하나의 문자 단위로 나누고, queue에 넣어주었다.

 

queue에서 사전에 없는 문자열이 될 때까지 문자를 하나씩 꺼내어 합쳐주고,

 

사전에 없는 문자열이 완성되었을 때

1. 사전에 put,

2. 그 전까지 합쳐진 사전에 있는 단어의 인덱스 출력

 

으로 로직을 구성했다.

 

import java.util.*;

class Solution {
    public int[] solution(String msg) {
        
        
        Map<String, Integer> index = index();
        int idx = index.get("Z") + 1;
        
        List<Integer> outputs = new ArrayList();
        
        String[] arr = msg.split("");
        Queue<String> queue = new LinkedList();
        for (String s : arr) queue.add(s);
        
        String s = queue.poll();
        while (!queue.isEmpty()) {
            
            String poll = queue.poll();
            String key = s + poll;
            if (index.containsKey(key)) {
                s = key;
                continue;
            } else {
                outputs.add(index.get(s));
                index.put(key, idx++);
                s = poll;
            }
            
        }
        
        outputs.add(index.get(s));
        
        return outputs.stream().mapToInt(a -> (int) a).toArray();
    }
    
    // 사전 초기화
    Map<String, Integer> index() {
        int num = 1;
        Map<String, Integer> index = new HashMap();
        for (int i = 'A'; i <= 'Z'; i++) {
            index.put(Character.toString((char)i), num++);
        }
        return index;
    }
}

'코딩테스트 > programmers' 카테고리의 다른 글

게임 맵 최단거리  (0) 2023.10.23
n진수 게임  (1) 2023.10.18
k진수에서 소수 개수 구하기  (0) 2023.10.16
전화번호 목록  (0) 2023.10.16
타겟 넘버  (0) 2023.10.16