Created
August 5, 2015 22:34
-
-
Save gabhi/c6d0dae679decde57cbd to your computer and use it in GitHub Desktop.
Basic string compression counting repeated characters
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 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