본문 바로가기

Programmers/Level2

문자열 압축

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
    public int solution(String s) {
        int answer = s.length();
        StringBuilder sb = new StringBuilder();
        int i, len = 1;
        String str;
 
        // 문자열 길이의 절반까지만 분할하여 탐색
        while (len <= s.length() / 2) {
            str = s.substring(00 + len);
 
            int cnt = 1, flag = 0;
            // len만큼 문자열 분할
            for (i = len; i < s.length(); i = i + len) {
                // 길이가 초과하는 경우 처리
                if (i + len > s.length()) {
                    if (cnt == 1)
                        sb.append(str);
                    else
                        sb.append(cnt + str);
                    sb.append(s.substring(i));
                    flag = 1;
                } else {
                    // 패턴이 달라지면
                    if (!str.equals(s.substring(i, i + len))) {
                        if (cnt == 1)
                            sb.append(str);
                        else
                            sb.append(cnt + str);
                        str = s.substring(i, i + len);
                        cnt = 1;
                    } else { // 패턴이 같으면
                        cnt++;
                    }
                }
            }
            if (flag == 0) {
                if (cnt == 1)
                    sb.append(str);
                else
                    sb.append(cnt + str);
            }
            // 길이의 최솟값만 저장
            if (sb.length() < answer)
                answer = sb.length();
            sb.delete(0, sb.length());
            len++;
        }
        return answer;
    }
}
cs

'Programmers > Level2' 카테고리의 다른 글

더 맵게  (0) 2021.07.12
타겟 넘버  (0) 2021.07.12
카카오프렌즈 컬러링북  (0) 2021.07.11
[1차] 뉴스 클러스터링  (0) 2021.07.09
기능개발  (0) 2021.07.09