Created
July 1, 2016 21:55
-
-
Save danielrobertson/cb50a23e53323d4a93df6fac60a73522 to your computer and use it in GitHub Desktop.
Cracking the Coding Chpt 1.6 String Compression
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
// aabccccaaa -> aabccccaaa | |
String compressString(String input) { | |
StringBuilder compressed = new StringBuilder(); | |
int count = 1; | |
String[] arr = input.split(""); | |
for(int i = 0; i < arr.length; i++) { | |
++count; | |
if(i + 1 >= arr.length || !arr[i + 1].equals(arr[i])) { | |
compressed.append(arr[i]); | |
compressed.append(Integer.toString(count)); | |
count = 0; | |
} | |
} | |
return compressed.toString().length() < input.length() ? compressed.toString() : input; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"Look ahead" and safety index check are better done in if statement instead of messing with the loop beginning or end conditions.