22
33class Solution {
44 public int solution (String s ) {
5- int strLen = s .length ();
6- if (strLen == 1 ) return 1 ;
7- int maxLen = strLen /2 ;
5+ int strLen = s .length (); // 문자열 길이
6+ int compressedMaxLen = strLen /2 ; // 최대 압축 길이
87
9- int answer = Integer . MAX_VALUE ;
8+ if ( strLen == 1 ) return 1 ; // 문자열 길이가 1이면 바로 반환
109
11- // 문자열을 len으로 압축했을때 문자열 길이를 구함
12- for (int len = 1 ; len <= maxLen ; len ++){
13- int zippedLen = zip (len ,s ); // 압축 문자열 길이
14- if (zippedLen < answer ){
15- answer = zippedLen ;
16- }
10+ int minLen = Integer .MAX_VALUE ; // 최솟값
11+ // 1부터 시작해서 최대 압축 길이까지 전부 압축 해보고 최솟값을 구함
12+ for (int compressedLen = 1 ; compressedLen <= compressedMaxLen ; compressedLen ++) {
13+ int len = compress (compressedLen , s ); // 압축 후 최솟값
14+ if (len < minLen ) minLen = len ;
1715 }
18-
19- return answer ;
16+ return minLen ;
2017 }
2118
22- // 문자열 s를 길이 len으로 압축한 길이
23- int zip (int len , String s ) {
24- // 압축 문자열 저장 스트링빌더
25- StringBuilder stringBuilder = new StringBuilder ();
26-
27- // 문자열의 시작 지점
28- for (int i = 0 ; i < s .length ();){
29- // len 단위로 자름
30- int endIdx = Math .min (i + len ,s .length ());
31- String currentString = s .substring (i ,endIdx );
32- int cnt = 1 ;
33-
34- int next = i + len ; // 다음 문자열
35- while (next < s .length ()){
36- int nextEndIdx = Math .min (next + len , s .length ());
37- String nextString = s .substring (next ,nextEndIdx );
19+ int compress (int compressedLen , String s ) {
20+ StringBuilder stringBuilder = new StringBuilder (); // 문자열을 저장
21+ // 0부터 시작
22+ for (int i = 0 ; i < s .length ();){
23+ int endIdx = Math .min (s .length (), i + compressedLen ); // 범위 초과 방지
24+ String current = s .substring (i ,endIdx );
3825
39- if (nextString .equals (currentString )){
40- cnt ++;
41- next += len ; // 다음 위치
42- } else {
43- break ; // 종료
26+ int nextIdx = endIdx ;
27+ int cnt = 1 ;
28+ while (nextIdx < s .length ()) {
29+ int nextEndIdx = Math .min (s .length (), nextIdx + compressedLen ); // 범위 초과 방지
30+ String next = s .substring (nextIdx ,nextEndIdx );
31+
32+ if (next .equals (current )){
33+ cnt ++;
34+ nextIdx += compressedLen ;
4435 }
36+ else break ;
4537 }
46-
47- // 겹치는 문자열이 있었던 경우
48- if (cnt > 1 ){
49- stringBuilder .append (cnt );
50- }
51- stringBuilder .append (currentString );
52- i =next ;
38+
39+ if (cnt > 1 ) stringBuilder .append (cnt );
40+ stringBuilder .append (current );
41+
42+ i = nextIdx ; // i값을 재설정
5343 }
54-
5544 return stringBuilder .length ();
5645 }
5746}
0 commit comments