본문 바로가기
Problem-solving/프로그래머스

프로그래머스 - (2020 KAKAO BLIND RECRUITMENT) 문자열 압축 (Java)

by taehee.kim.dev 2020. 11. 23.

programmers.co.kr/learn/courses/30/lessons/60057

 

코딩테스트 연습 - 문자열 압축

데이터 처리 전문가가 되고 싶은 어피치는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문자

programmers.co.kr

import java.util.Arrays;

// 압축했을 때, 가장 짧은 것의 길이는?
class Solution {
    public int solution(String s) {

        int[] compLengths = new int[s.length()];

        for (int compSize = 1; compSize <= s.length(); compSize++){

            String initialStr = s;
            String totalCompStr = "";
            String curCompStr = "";

            int curCompCount = 1;

            int startIndex = 0;
            int endIndex = compSize;

            while (endIndex <= s.length()){

                String subS = s.substring(startIndex, endIndex);
                initialStr = s.substring(endIndex);

                if (!curCompStr.equals(subS)){

                    if (curCompCount > 1){
                        totalCompStr += curCompCount;
                    }
                    totalCompStr += curCompStr;

                    curCompStr = subS;
                    curCompCount = 1;
                }else{
                    curCompCount += 1;
                }

                startIndex = endIndex;
                endIndex += compSize;
            }
            if (curCompCount > 1){
                totalCompStr += curCompCount;
            }
            totalCompStr += curCompStr;
            totalCompStr += initialStr;
            compLengths[compSize - 1] = totalCompStr.length();
        }

        Arrays.sort(compLengths);
        return compLengths[0];
    }
}

댓글