programmers_문자열 압축_java

2023. 5. 15. 11:39Algorithm/Programmers

728x90

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

 

프로그래머스

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

programmers.co.kr

 

class Solution {
public int solution(String s) {
        int sLength = s.length();
        int answer = sLength;
        for(int i = 1; i<=sLength/2; i++){
            answer = Math.min(answer , zip(s, sLength, i));
        }

        return answer;
    }

    public int zip(String s, int sLength, int zipSize){
        StringBuilder sb = new StringBuilder();
        String before = s.substring(0, zipSize);
        int cnt = 1;
        for (int i = zipSize; i<sLength; i+=zipSize){
            if (sLength - i >= zipSize){ // 남은 길이가 충분한 경우
                String next = s.substring(i, i+zipSize);
                if (before.equals(next)){ // 문자열 일치
                    cnt++;
                }else { // 불일치
                    if (cnt > 1){
                        sb.append(cnt);
                    }
                    sb.append(before);
                    cnt = 1;
                    before = next;
                }

                if (i + zipSize >= sLength){ // 딱 떨어지는 경우 (zipSize = 1 등)
                    if (cnt > 1){
                        sb.append(cnt);
                    }
                    sb.append(before);
                    sb.append(s.substring(i + zipSize));
                }
                
            }else{ // 남은 길이가 충분하지 않은 경우
                if (cnt > 1){
                    sb.append(cnt);
                }
                sb.append(before);
                sb.append(s.substring(i));
            }
        }

        return sb.length();
    }
}