Skip to content

Instantly share code, notes, and snippets.

@danielrobertson
Created July 1, 2016 21:55
Show Gist options
  • Select an option

  • Save danielrobertson/cb50a23e53323d4a93df6fac60a73522 to your computer and use it in GitHub Desktop.

Select an option

Save danielrobertson/cb50a23e53323d4a93df6fac60a73522 to your computer and use it in GitHub Desktop.
Cracking the Coding Chpt 1.6 String Compression
// 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;
}
@danielrobertson

Copy link
Copy Markdown
Author

"Look ahead" and safety index check are better done in if statement instead of messing with the loop beginning or end conditions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment