CodingTest/Programmers

[Programmers] 문자열 압축

창브로 2025. 5. 12. 19:32

[문제 링크]

https://school.programmers.co.kr/learn/courses/30/lessons/60057?language=java

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

[풀이 과정]

한자리부터 글자의 반까지 하나하나 잘라보며 currentStr 와 새로운 단어가 같으면

count++ 아니면 count의 숫자와 전의 단어를 저장 후 새로운 단어를 currentStr에 넣고

count를 1로 초기화하여 반복한 후 minValue와 완성된 String의 length를 비교하여 정답을 구합니다.

 

[코드]

class Solution {
    public int solution(String s) {
        int n = s.length();
        int minValue = n;
        
        for(int i = 1; i <= n / 2; i++) {
            String currentStr = s.substring(0,i);
            String answer = "";
            int count = 1;
            for(int j = 1; j <= n/i+1; j++) {
                String str = "";
                
                if(i*j+i > n) {
                    if(count > 1) {
                        answer += String.valueOf(count);
                        answer += currentStr;
                    } else {
                        answer += currentStr;
                    }
            
                    answer += s.substring(i*j, n);
                    break;
                } else {
                    str = s.substring(i*j, (i*j) + i);
                    
                    if(currentStr.equals(str)) {
                        count++;
                    } else {
                        if(count > 1) {
                            answer += String.valueOf(count) + currentStr;
                            
                        } else {
                            answer += currentStr;
                        }
                        
                        currentStr = str;
                        count = 1;
                        
                    }
                }
            }
            
            if(minValue > answer.length()) {
                minValue = answer.length();
            }
            
        }
        
        
        return minValue;
    }
}

[회고]

어떻게 풀지는 생각을 했지만 중복이 없을때도 1abc 이런 식으로 넣어주는 곳에서 틀려

많이 헤맸습니다.

구현하는 연습을 더욱 더 해야 할 것 같습니다.

 

 

 

 

질문과 피드백은 언제나 환영입니다.

감사합니다.