import java.util.ArrayList;
public class StringCompression {
public int solution(String s) {
ArrayList<String> list = new ArrayList<String>();
String str = "";
String temp = "";
int min = s.length();
int count = 1;
int i = 0, j = 1;
if (s.length() == 1) {
return 1;
}
while (true) {
int k = i + j;
if (k > s.length()) {
k = s.length();
}
str = s.substring(i, k);
list.add(str);
i += j;
if (i >= s.length()) {
for (int h = 1; h < list.size(); h++) {
if (list.get(h - 1).equals(list.get(h))) {
count++;
} else {
if (count == 1) {
temp += list.get(h - 1);
} else {
temp += Integer.toString(count) + list.get(h - 1);
}
count = 1;
}
if (h == list.size() - 1) {
if (count == 1) {
temp += list.get(h);
} else {
temp += Integer.toString(count) + list.get(h);
}
count = 1;
}
}
if (min > temp.length()) {
min = temp.length();
}
temp = "";
list.removeAll(list);
j++;
i = 0;
if (j > s.length() / 2) {
break;
}
}
}
return min;
}
public static void main(String[] args) {
StringCompression a = new StringCompression();
System.out.println(a.solution("a"));
System.out.println(a.solution("aabbaccc"));
System.out.println(a.solution("ababcdcdababcdcd"));
System.out.println(a.solution("abcabcdede"));
System.out.println(a.solution("abcabcabcabcdededededede"));
System.out.println(a.solution("xababcdcdababcdcd"));
}
}
- 반복문의 조건으로 s.length() 까지 할 필요 없이 s.length()/2 까지만 확인해도 된다. 왜냐하면 예를 들어 'abcdabcdee' 라는 10자리의 문자열이 있을 때, 5개 이상, 즉 6개로 잘랐을 때 'abcdab', 'cdee' 로 잘라진다면, 잘려진 첫번째 문자열의 크기가 원본 문자열의 절반 크기보다 클 때 어차피 뒷 부분에 반복이 되지 않는다.
Test Case 5 : 문자열 s 가 'a' 와 같이 한 글자일 때 처리를 해주어야 한다.
length() : String의 길이, length : 배열의 길이, size() : Collections의 크기