Skip to content

Instantly share code, notes, and snippets.

@thetekst
Last active October 15, 2022 22:11
Show Gist options
  • Save thetekst/46f0d56295ce40cd887a105ccb42c691 to your computer and use it in GitHub Desktop.
Save thetekst/46f0d56295ce40cd887a105ccb42c691 to your computer and use it in GitHub Desktop.
Write string compressor
public static void main(String[] args) {
final var line = "abaabbbc"; //Expected result: aba2b3c
final var chars = line.toCharArray();
int count = 0;
char prev = ' ';
final var result = new ArrayList<Character>();
for (char current : chars) {
if (current == prev) {
count++;
} else {
if (count > 1) {
result.add((char) (count + '0'));
}
result.add(current);
prev = current;
count = 1;
}
}
System.out.println(result.stream().map(String::valueOf).collect(Collectors.joining()));
}
@thetekst
Copy link
Author

compress-algorithms drawio

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