Closed rygh4775 closed 5 years ago
문자열을 iterate 하면서 이번 문자와 다르면 문자와 반복 횟수를 더하는 방식으로 할 수 있습니다. 문자열 더하는 비용이 크므로 StringBuffer를 사용하면 유리합니다.
public String compress(String str){
StringBuffer sb = new StringBuffer();
Character prevCh = null;
int count = 0;
for(int i =0; i < str.length(); i++){
count++;
if( i +1 > str.length() || str.charAt(i) != str.charAt(i+1)){
sb.append(str.charAt(i));
sb.append(count);
count = 0;
}
}
String compressedStr = sb.toString();
return str.length() <= compressedStr.length() ? str : compressedStr;
}
String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).