본문 바로가기
카테고리 없음

[프로그래머스] 압축 [java]

by 근즈리얼 2021. 7. 7.
728x90

문제

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

 

코딩테스트 연습 - [3차] 압축

TOBEORNOTTOBEORTOBEORNOT [20, 15, 2, 5, 15, 18, 14, 15, 20, 27, 29, 31, 36, 30, 32, 34]

programmers.co.kr

 


문제 풀이

 

가장 핵심적으로 두 가지만 생각하면 풀 수 있는 문제였다.

1. 문자열 tmp에 문자를 하나씩 더해가면서 map에 있으면 문자를 하나 더 추가하고

없으면 tmp값을 map에 추가하고 tmp의 마지막 문자를 지우고 ans리스트에 추가한다.

2. 문자를 하나씩 더해가던 중 마지막 문자를 만났을 때 마지막 문자를 포함한 tmp가 map에 있으면 그대로 ans에 추가해주면 되고 없으면 그대로 map에 추가하고 마지막 문자만 한번더 while문을 돌려주면 된다.

 

**주의

1. 문자열 분석하는 마지막 부분에 ans리스트에 넣을 때 tmp의 마지막 문자를 빼는 것

2. 현재 가리키는 곳이 내가 넣으려는 문자의 +1이라는 것을 고려해 i--를 하는 것을 주의해야한다.

 

코드

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class compression {
    public static void main(String[] args) {
        String msg = "KAKAO";
        compression c = new compression();
        System.out.println(Arrays.toString(c.solution(msg)));
    }

    public int[] solution(String msg){
        HashMap<String, Integer> map = new HashMap<>();
        ArrayList<Integer> ans = new ArrayList<>();

        char ch = 'A';
        for(int i = 1; i<27;i++){
            map.put(ch+"",i);
            ch++;
        }
        int mapNum = 27;
        boolean flag = false;
        for(int i = 0; i<msg.length();i++){
            String tmp = msg.charAt(i) + "";
            while(map.containsKey(tmp)){
                i++;
                if(i == msg.length()){
                    flag = true;
                    break;
                }
                tmp += msg.charAt(i);
            }
            if(flag){
                ans.add(map.get(tmp));
                break;
            }
            ans.add(map.get(tmp.substring(0,tmp.length()-1)));
            map.put(tmp,mapNum++);
            i--;
        }
        int[] answer = new int[ans.size()];
        for(int i = 0; i<ans.size();i++){
            answer[i] = ans.get(i);
        }
        return answer;
    }
}
728x90

댓글