Created
February 7, 2020 07:20
-
-
Save keehyun2/e0df2be6700593a18e48812bf8b1df8c to your computer and use it in GitHub Desktop.
문바열 압축 - 수행시간 개선... (다른코드 많이 참조했습니다)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StringZip { | |
public int solution(String s) { | |
//System.out.println(s); | |
int minLength = s.length(); | |
for (int unit = 1; unit <= s.length() / 2; unit++) { // for #01 | |
String composeStr = ""; | |
int repeatCnt = 1; | |
String preStr = ""; | |
String postStr = s; | |
for (int i = unit; i < s.length() + 1 ; i+=unit) { // for #02 | |
preStr = postStr.substring(0, unit); | |
postStr = postStr.substring(unit); // unit ~ 문자열 끝까지 절단 | |
// System.out.println(unit + ", " + preStr + ", " +postStr + ", " + i); | |
if(postStr.startsWith(preStr)) { | |
// i 위치에서 preStr 와 postStr 앞부분이 일치하는 경우 | |
repeatCnt = repeatCnt + 1; // 반복횟수 1 추가 | |
}else { | |
// i 위치에서 preStr 와 postStr 앞부분이 일치하지 않는 경우 - 1. 문자열 끝에 길이가 안맞는 경우 , 2 문자가 다른경우 | |
if(repeatCnt > 1) { // 반복횟수가 1보다 큰경우 | |
composeStr = composeStr + String.valueOf(repeatCnt) + preStr; | |
repeatCnt = 1; | |
}else { | |
composeStr = composeStr + preStr; | |
} | |
} | |
} | |
composeStr = composeStr + postStr; | |
// System.out.println(unit + ", "+composeStr); | |
minLength = Math.min(composeStr.length(), minLength); | |
} | |
return minLength; | |
} | |
public static void main(String[] args) { | |
System.out.println(new StringZip().solution("a")); // 1 | |
System.out.println(new StringZip().solution("aabbaccc")); // 7 | |
System.out.println(new StringZip().solution("ababcdcdababcdcd")); // 9 | |
System.out.println(new StringZip().solution("abcabcdede")); // 8 | |
System.out.println(new StringZip().solution("abcabcabcabcdededededede")); // 14 | |
System.out.println(new StringZip().solution("xababcdcdababcdc")); // 16 | |
System.out.println(new StringZip().solution("aaaaaaaaaa")); // 3 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment