정답
class Solution {
public int solution(String s) {
int len = s.length();
int answer = len;
for(int i=1; i<=len/2; i++){
String str1 = s.substring(0, i);
int cnt = 1;
int min = 0;
for(int j=i; j<=len; j+=i){
String str2 = s.substring(j, j+i > len ? len : j+i);
if(str1.equals(str2)){
cnt++;
}else{
min += str1.length();
if(cnt > 1){
min += (int)Math.log10(cnt) + 1;
}
str1 = str2;
cnt = 1;
}
}
min += str1.length();
if(cnt > 1){
min += (int)Math.log10(cnt) + 1;
}
answer = Math.min(answer, min);
}
return answer;
}
}
분석
//end index에 3항 연산자를 사용하여 아웃바운드 방지
String str2 = s.substring(j, j+i > len ? len : j+i);
계속 제출에서 실패한 코드
class Solution {
public int solution(String s) {
int len = s.length();
int answer = len;
for(int i=1; i<=len/2; i++){
String str1 = s.substring(0, i);
int cnt = 1;
int min = 0;
for(int j=i; j<=len; j+=i){
String str2 = s.substring(j, j+i > len ? len : j+i);
if(str1.equals(str2)){
cnt++;
}else{
min += str1.length();
if(cnt > 1){
min++; //실패 원인
}
str1 = str2;
cnt = 1;
}
}
min += str1.length();
if(cnt > 1){
min++; //실패 원인
}
answer = Math.min(answer, min);
}
return answer;
}
}