본문 바로가기
Problem Solving

[프로그래머스] L2 문자열 압축 / 2020 카카오 블라인드 채용

by JYHAN 2020. 12. 9.

카카오

[프로그래머스] L2 문자열 압축 / 2020 카카오 블라인드 채용

[풀이]

슬라이딩 윈도우로 풀릴 것 같은 느낌...

 

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
class Solution {
    public int solution(String s) {
        int answer = Integer.MAX_VALUE;
        if(s.length()==1return 1;
        for(int unit=1; unit<=s.length()/2; unit++){
            int cnt = 1;      // 같은 문자열 카운트
            String str = ""// 해당 unit에서 만들어진 문자열
            String next = "";
            String slice = s.substring(0, unit);
            for(int i=unit; i<s.length(); i+=unit){
                int endIndex = (i+unit)>s.length()?s.length():i+unit;
                next = s.substring(i, endIndex);
                if(slice.equals(next)){
                    cnt++;
                }else{
                    if(cnt==1) str += slice;
                    else str +=(Integer.toString(cnt)+slice);
                    slice = next; // 새로 자른 문자열
                    cnt = 1;
                }
                if(i+unit >= s.length()){ // 종료
                    if(cnt == 1){
                        str += s.substring(i,endIndex);
                        break;
                    }else{
                        str += (Integer.toString(cnt)+slice);
                        break;
                    }
                }
                if(endIndex==s.length()) break;
            }
            if(answer>str.length()) answer = str.length();
        }
        return answer;
    }
}
cs

댓글