[programmers] 문자열 압축

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

회고) 앞에서 부터 정해진 step 만큼 자르는 것.. 문제좀 잘 보자..

class Solution {
    public int solution(String s) {
        int minLength = s.length();

        for(int step = 1; step <= s.length() / 2 ; step++){
            StringBuilder compressed = new StringBuilder();
            String prev = s.substring(0, step);
            int count = 1;

            for(int j = step; j<s.length(); j += step){
                int end = Math.min(j+step, s.length());
                String current = s.substring(j, end);

                if(prev.equals(current)){
                    count++;
                }else{
                    if(count > 1){
                        compressed.append(count);
                    }
                    compressed.append(prev);
                    prev = current;
                    count = 1;
                }
            }

            if(count > 1){
                compressed.append(count);
            }
            compressed.append(prev);

            minLenth = Math.min(minLenth, compressed.length());
        }

        return minLength;
    }
}

© 2023 Lee. All rights reserved.