Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created August 5, 2015 22:34
Show Gist options
  • Save gabhi/c6d0dae679decde57cbd to your computer and use it in GitHub Desktop.
Save gabhi/c6d0dae679decde57cbd to your computer and use it in GitHub Desktop.
Basic string compression counting repeated characters
public String compress(String str) {
if (str.isEmpty()) {
return "";
}
char[] chars = str.toCharArray();
StringBuilder builder = new StringBuilder();
int count = 1;
char prev = chars[0];
for (int i = 1; i < chars.length; i++) {
char current = chars[i];
if (current == prev) {
count++;
} else {
builder.append(prev).append(count);
count = 1;
}
prev = current;
}
return builder.append(prev).append(count).toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment