• 문제 링크
 

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

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

programmers.co.kr

 

 

  • 설명

 i개의 갯수만큼 문자열을 잘라 현재 문자열과 전 문자열을 비교하여 압축

 

 

  • 코드
public class Solution {
    public int solution(String s) {
      int answer = s.length();

      for (int i = 1; i <= s.length() / 2; i++) {
        int compLength = compression(s, i).length();
        answer = Math.min(answer, compLength);
      }

      return answer;
    }

    private String compression(String string, int i) {

      int count = 1;
      String compression = "";
      String pattern = "";

      for (int j = 0; j <= string.length() + i; j += i) {

        String nowString;

        // 전 문자열과 비교할 현재 문자열
        if (j >= string.length()) { // 현재 문자열이 없을 때
          nowString = "";
        } else if (string.length() < j + i) { // 마지막 현재 문자열일 때
          nowString = string.substring(j);
        } else {
          nowString = string.substring(j, j + i);
        }

        // 1. 전 문자열이랑 똑같은지 비교한다. (맨 처음이면 비교 X)
        if (j != 0) {
          if (nowString.equals(pattern)) { // 같으면
            count++;
          } else if (count >= 2) { // 다르고 count가 2회 이상
            compression += count + pattern;
            count = 1;
          } else { // 압축 불가능
            compression += pattern;
          }
        }
        pattern = nowString;
      }

      return compression;
    }
}

+ Recent posts