Last active
August 29, 2015 14:02
-
-
Save walkingtospace/8c64f69976719a52a2ca to your computer and use it in GitHub Desktop.
cracking the coding interview 5th 1.5
This file contains 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
1.5 Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. | |
extra memory : none | |
Time complxity : O(n) | |
잘못된 입력은 없다고 가정. | |
test case : "", "a", "abc", "abbcc", "aabcc", "aabbc", "aaaaa" | |
test case 작성 기준 :빈문자열, 한글자, 모두 동일 substring, 1글자 짜리 substring의 위치(첫,중앙,끝), 나머지는 다 동일. | |
string compressStr(string input) { | |
int length = input.length(); | |
string output =""; | |
char c = input[0]; | |
int index = 0; | |
if(length <= 0) return ""; //or throw 처리 | |
for(int i=0 ; i<length ; i++) { | |
if(input[i] == c) { | |
index++; | |
} else { | |
output += (c + to_string(index)); | |
index = 1; | |
c = input[i]; | |
} | |
} | |
output += (c + to_string(index)); | |
if(output.length() >= input.length()) return input; | |
else return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment