Last active
October 15, 2022 22:11
-
-
Save thetekst/46f0d56295ce40cd887a105ccb42c691 to your computer and use it in GitHub Desktop.
Write string compressor
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
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())); | |
} |
Author
thetekst
commented
Oct 15, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment