20220204_알고리즘

Minseok-Choi·2022년 2월 4일
0

알고리즘

목록 보기
12/13
post-thumbnail

프로그래머스_문자열 압축

  • 반복이후에 나머지 문자열을 넣어주는 것을 생각못해서 시간이 많이 걸린 문제다.
  • 반복문을 만들때, 변수(i,j)를 요구사항에 맞춰서 넣는 연습이 많이 된 것 같다.
  • 디버깅하면서 조건문을 많이 수정했다.
  • 반복에서 여러가지 조건이 들어갈때, 작은 단위의 메서드부터 설계하기가 쉽지않다.
class Solution {
    public int solution(String s) {
        int answer = s.length();
        
        for (int i = 1; i <= s.length() / 2; i++) {
            
            String value = s.substring(0, i);
            StringBuilder compression = new StringBuilder();
            int count = 1;

            for (int j = i; j <= s.length(); j += i) {
                
                int end = Math.min(j + i, s.length());
                String next = s.substring(j, end);
                
                if (value.equals(next)) {
                    count++;
                    continue;
                }
                
                if(count == 1) {
                    compression.append(value);
                } else {
                    compression.append(count).append(value);
                    count = 1;
                }
                
                value = next;

            }
            compression.append(value);
            answer = Math.min(answer, result.length());
        }
        return answer;
    }
}
profile
차곡차곡

0개의 댓글